Python dictionary increment

给你一囗甜甜゛ 提交于 2019-12-03 06:38:15

问题


In Python it's annoying to have to check whether a key is in the dictionary first before incrementing it:

if key in my_dict:
  my_dict[key] += num
else:
  my_dict[key] = num

Is there a shorter substitute for the four lines above?


回答1:


An alternative is:

my_dict[key] = my_dict.get(key, 0) + num



回答2:


You have quite a few options. I like using Counter:

>>> from collections import Counter
>>> d = Counter()
>>> d[12] += 3
>>> d
Counter({12: 3})

Or defaultdict:

>>> from collections import defaultdict
>>> d = defaultdict(int)  # int() == 0, so the default value for each key is 0
>>> d[12] += 3
>>> d
defaultdict(<function <lambda> at 0x7ff2fe7d37d0>, {12: 3})



回答3:


What you want is called a defaultdict

See http://docs.python.org/library/collections.html#collections.defaultdict




回答4:


transform:

if key in my_dict:
  my_dict[key] += num
else:
  my_dict[key] = num

into the following using setdefault:

my_dict[key] = my_dict.setdefault(key, 0) + num



回答5:


There is also a little bit different setdefault way:

my_dict.setdefault(key, 0)
my_dict[key] += num

Which may have some advantages if combined with other logic.



来源:https://stackoverflow.com/questions/12992165/python-dictionary-increment

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!