Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to add to a dictionary value or create if not exists

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

like image 936
WeaselFox Avatar asked Jul 17 '14 10:07

WeaselFox


4 Answers

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}
like image 187
sundar nataraj Avatar answered Nov 17 '22 22:11

sundar nataraj


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})
like image 30
Jon Clements Avatar answered Nov 18 '22 00:11

Jon Clements


>>> 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
like image 7
Marco Mariani Avatar answered Nov 17 '22 22:11

Marco Mariani


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
like image 3
dericke Avatar answered Nov 17 '22 23:11

dericke