字典(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)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值