Python字典增量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12992165/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python dictionary increment
提问by Paul S.
In Python it's annoying to have to check whether a key is in the dictionary first before incrementing it:
在 Python 中,在增加一个键之前必须先检查它是否在字典中是很烦人的:
if key in my_dict:
my_dict[key] += num
else:
my_dict[key] = num
Is there a shorter substitute for the four lines above?
上面四行有更短的替代品吗?
采纳答案by Nicola Musatti
An alternative is:
另一种选择是:
my_dict[key] = my_dict.get(key, 0) + num
回答by Eric
What you want is called a defaultdict
你想要的叫做 defaultdict
See http://docs.python.org/library/collections.html#collections.defaultdict
请参阅http://docs.python.org/library/collections.html#collections.defaultdict
回答by Blender
You have quite a few options. I like using Counter:
你有很多选择。我喜欢使用Counter:
>>> from collections import Counter
>>> d = Counter()
>>> d[12] += 3
>>> d
Counter({12: 3})
Or defaultdict:
或者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})
回答by dnozay
transform:
转变:
if key in my_dict:
my_dict[key] += num
else:
my_dict[key] = num
into the following using setdefault:
进入以下使用setdefault:
my_dict[key] = my_dict.setdefault(key, 0)?+ num
回答by Roman Susi
There is also a little bit different setdefaultway:
还有一点不同的setdefault方式:
my_dict.setdefault(key, 0)
my_dict[key] += num
Which may have some advantages if combined with other logic.
如果与其他逻辑结合,可能会有一些优势。
回答by Sayan Maity
Any one of .getor .setdefaultcan be used:
.get或.setdefault可以使用以下任何一种:
.get()give default value passed in the function if there is no valid key
.get()如果没有有效的键,则给出函数中传递的默认值
my_dict[key] = my_dict.get(key, 0) + num
.setdefault ()create a key with default value passed
.setdefault ()创建一个传递默认值的键
my_dict[key] = my_dict.setdefault(key, 0) + num

