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
you can use
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}
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})
>>> 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
collections.Counter
is the best for the specific use case you gave, but for a more general solution that doesn't require importing anything, use dict.setdefault()
:
d[key] = d.setdefault(key, 0) + 1
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With