how to add to a dictionary value or create if not exists
·
Answer a question
I want to add to a value in a dictionary storing counters:
d[key] += 1
but sometimes the key will not exist yet. Checking to see if the key exists seems too ugly. Is there a nice and pythonic one liner for this - add if the key exists, or create the value 1 if the key is not in the dict.keys ?
thanks
Answers
You can use collections.Counter - this guarantees that all values are 1 or more, supports various ways of initialisation, and supports certain other useful abilities that a dict/defaultdict don't:
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})
更多推荐

所有评论(0)