Update Dictionary By Incrementing
>>> D1 = {'potatoes':2.67,'sugar':1.98,'cereal':5.99,'crisps':1.09} >>> D2 = {'parsley':0.76,'cereal':3.22} >>> D1 = updateDictionaryByIncrementing(D1,
Solution 1:
You can use looping over the keys:
forkeyin D2:
D1[key] = D1.get(key, 0) + D2[key]
or you can use collections.Counter()
objects:
from collections import Counter
D1 = dict(Counter(D1) + Counter(D2))
Demo of the latter technique:
>>> from collections import Counter
>>> D1 = {'potatoes':2.67,'sugar':1.98,'cereal':5.99,'crisps':1.09}
>>> D2 = {'parsley':0.76,'cereal':3.22}
>>> Counter(D1) + Counter(D2)
Counter({'cereal': 9.21, 'potatoes': 2.67, 'sugar': 1.98, 'crisps': 1.09, 'parsley': 0.76})
>>> dict(Counter(D1) + Counter(D2))
{'cereal': 9.21, 'parsley': 0.76, 'sugar': 1.98, 'potatoes': 2.67, 'crisps': 1.09}
Solution 2:
Counter is a convenient way to do this (counts don't have to be integers)
>>> from collections import Counter
>>> D1 = {'potatoes':2.67,'sugar':1.98,'cereal':5.99,'crisps':1.09}
>>> D2 = {'parsley':0.76,'cereal':3.22}
>>> Counter(D1) + Counter(D2)
Counter({'cereal': 9.21, 'potatoes': 2.67, 'sugar': 1.98, 'crisps': 1.09, 'parsley': 0.76})
You could also use dict.update
list this:
>>> D1.update((k, D1.get(k, 0) + v) for k, v in D2.items())
>>> D1
{'potatoes': 2.67, 'parsley': 0.76, 'crisps': 1.09, 'cereal': 9.21, 'sugar': 1.98}
Solution 3:
If you want to increment the values of the dictionaries, you could implement updateDictionaryByIncrementing
like this:
def updateDictionaryByIncrementing(a,b):
c = dict()
for k,v in b.items():
c[k] = a.get(k,0.0) + v
return c
By using the get
method of the a
dictionary, the case where a
does not have a value with the given key is handled using a default value.
Solution 4:
You can use dictionary comprehension, like this
D1 = {'potatoes': 2.67, 'sugar': 1.98, 'cereal': 5.99, 'crisps': 1.09}
D2 = {'parsley': 0.76, 'cereal': 3.22}
print {key: D1.get(key, 0) + D2.get(key, 0) for key in D1.viewkeys() | D2}
Output
{'cereal': 9.21,
'crisps': 1.09,
'parsley': 0.76,
'potatoes': 2.67,
'sugar': 1.98}
Solution 5:
You can do that using try
/except
as follows:
for k,v in D2.items():
try:
D1[k] += v
except KeyError:
D1[k] = v
Post a Comment for "Update Dictionary By Incrementing"