Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add values from two dictionaries

dict1 = {a: 5, b: 7}
dict2 = {a: 3, c: 1}

result {a:8, b:7, c:1}

How can I get the result?

like image 314
Peter Avatar asked Aug 16 '17 12:08

Peter


2 Answers

this is a one-liner that would do just that:

dict1 = {'a': 5, 'b': 7}
dict2 = {'a': 3, 'c': 1}

result = {key: dict1.get(key, 0) + dict2.get(key, 0)
          for key in set(dict1) | set(dict2)}
# {'c': 1, 'b': 7, 'a': 8}

note that set(dict1) | set(dict2) is the set of the keys of both your dictionaries. and dict1.get(key, 0) returns dict1[key] if the key exists, 0 otherwise.


this works on a more recent python version:

{k: dict1.get(k, 0) + dict2.get(k, 0) for k in dict1.keys() | dict2.keys()}
like image 106
hiro protagonist Avatar answered Nov 08 '22 21:11

hiro protagonist


You can use collections.Counter which implements addition + that way:

>>> from collections import Counter
>>> dict1 = Counter({'a': 5, 'b': 7})
>>> dict2 = Counter({'a': 3, 'c': 1})
>>> dict1 + dict2
Counter({'a': 8, 'b': 7, 'c': 1})

if you really want the result as dict you can cast it back afterwards:

>>> dict(dict1 + dict2)
{'a': 8, 'b': 7, 'c': 1}
like image 43
MSeifert Avatar answered Nov 08 '22 21:11

MSeifert