如何添加到字典值或创建(如果不存在)

Wea*_*Fox 2 python python-3.x

我想在存储计数器的字典中添加一个值:

d[key] += 1
Run Code Online (Sandbox Code Playgroud)

但有时钥匙还不存在.检查密钥是否存在似乎太难看了.是否有一个漂亮的pythonic单线程 - 如果密钥存在则添加,或者1如果密钥不在dict.keys中则创建值?

谢谢

Jon*_*nts 8

您可以使用collections.Counter- 这保证了所有值都是1或更多,支持各种初始化方式,并支持某些其他有用的功能dict/defaultdict不支持:

from collections import Counter

values = ['a', 'b', 'a', 'c']

# Take an iterable and automatically produce key/value count
counts = Counter(values)
# Counter({'a': 2, 'c': 1, 'b': 1})
print counts['a'] # 2
print counts['d'] # 0
# Note that `counts` doesn't have `0` as an entry value like a `defaultdict` would
# a `dict` would cause a `KeyError` exception
# Counter({'a': 2, 'c': 1, 'b': 1})

# Manually update if finer control is required
counts = Counter()
for value in values:
    counts.update(value) # or use counts[value] += 1
# Counter({'a': 2, 'c': 1, 'b': 1})
Run Code Online (Sandbox Code Playgroud)


sun*_*raj 7

您可以使用

d={}
key='sundar'

d[key]=d.get(key,0)+1
print d
#output {'sundar': 1}
d[key]=d.get(key,0)+1
print d
#output {'sundar': 2}
Run Code Online (Sandbox Code Playgroud)

  • @WeaselFox 事实上,我喜欢它,我希望对每个否决票添加评论是强制性的。 (2认同)

Mar*_*ani 5

>>> import collections
>>> d = collections.defaultdict(int)
>>> key = 'foo'
>>> d[key] += 1
>>> d
defaultdict(<type 'int'>, {'foo': 1})
>>> d[key]
1
>>> d[key] += 1
>>> d[key]
2
Run Code Online (Sandbox Code Playgroud)

  • @WeaselFox只是要小心执行一个操作......`defaultdict`触发`__getitem__`上的`__default__`行为,所以如果你只是`foo [key]`它不存在,你会得到一个在你的柜台输入`key:0` (2认同)