Reputation: 974
How to sum the values in a python dict when I add the same key?
d = {'key1':10,'key2':14,'key3':47}
d['key1'] = 20
After the above the value of d['key1']
should be 30.
Is this possible?
Upvotes: 1
Views: 614
Reputation: 908
d = {'key1':10,'key2':14,'key3':47}
Solution in One line to sum the values in a python dict when we add the same key:
d['key1'] = dict.get('key1', 0) + 20
Explanation:
dict.get('key1', 0)
this will return the the key value if found in dict otherwise return default value as 0
Upvotes: 0
Reputation: 39638
from collections import defaultdict
d = defaultdict(int)
d['key1'] += 20
Upvotes: 4
Reputation: 251196
You can use collections.Counter
:
>>> from collections import Counter
>>> d =Counter()
>>> d.update({'key1':10,'key2':14,'key3':47})
>>> d['key1'] += 20
>>> d['key4'] += 50 # Also works for keys that are not present
>>> d
Counter({'key4': 50, 'key3': 47, 'key1': 30, 'key2': 14})
Counter has some advantages:
>>> d1 = Counter({'key4': 50, 'key3': 4})
#You can add two counters
>>> d.update(d1)
>>> d
Counter({'key4': 100, 'key3': 51, 'key1': 30, 'key2': 14})
You can get a list of sorted items(based on the value) using most_common()
:
>>> d.most_common()
[('key4', 100), ('key3', 51), ('key1', 30), ('key2', 14)]
Timing comparisons:
>>> keys = [ random.randint(0,1000) for _ in xrange(10**4)]
>>> def dd():
d = defaultdict(int)
for k in keys:
d[k] += 10
...
>>> def count():
d = Counter()
for k in keys:
d[k] += 10
...
>>> def simple_dict():
... d = {}
... for k in keys:
... d[k] = d.get(k,0) + 10
...
>>> %timeit dd()
100 loops, best of 3: 3.47 ms per loop
>>> %timeit count()
100 loops, best of 3: 10.1 ms per loop
>>> %timeit simple_dict()
100 loops, best of 3: 5.01 ms per loop
Upvotes: 5
Reputation: 706
try:
dict[key1]+=20 #The value you wanted
except KeyError:
dict[key1]=10 #The initial Value
Upvotes: 0