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})
Logo

Python社区为您提供最前沿的新闻资讯和知识内容

更多推荐