字典(python)

值+=1

  1. add an element to a dict if it does not exist or increment it by 1 if it does.
  • Use the get() method to return the current value or 0 if the key does not exist, then add 1 and assign it back to the key1:
d[key] = d.get(key, 0) + 1
  • Use the setdefault() method to set the default value to 0 if the key does not exist, then add 1 and assign it back to the key2:
d[key] = d.setdefault(key, 0) + 1
  • Use the defaultdict class from the collections module to create a dict that automatically assigns 0 to a missing key, then add 1 and assign it back to the key3:
from collections import defaultdict
d = defaultdict(int)
d[key] += 1

排序

  • 先按照values降序排序,后按照keys 的长度升序排序,最后按照keys的字典序排序.
words_dict_sorted = {k:v for k,v in sorted(words_dict.items(), key=lambda item:(-item[1],len(item[0]),item[0]))}


sorted_dict = dict(sorted(my_dict.items(), key=lambda x: (-len(x[1]), x[1])))

  • 如果你想对 Python 字典中的每一组 key-value 的 value 按照长度进行降序排序,然后再按照字典序排序,你可以使用字典的items 方法来遍历字典中的每一个 key-value 对,然后对每一个 value 进行排序。
my_dict = {
    "apple": [4, 21, 5],
    "banana": [3],
    "grape": [12, 23, 34, 54],
    "orange": [45, 34]
}

for key, value in my_dict.items():
    sorted_values = sorted(value, key=lambda x: (-len(str(x)), str(x)))
    my_dict[key] = sorted_values

print(my_dict)

你可能感兴趣的:(python)