If the input is
d1={'A':5,'B':6,'C':8}
d2={'A':4,'B':9,'E':2}
I want the output to be
d3={'A':9,'B':15,'C':8,'E':2}
If the input is
d1={'A':5,'B':6,'C':8}
d2={'A':4,'B':9,'E':2}
I want the output to be
d3={'A':9,'B':15,'C':8,'E':2}
Use collections.Counter
for counting:
from collections import Counter
d3 = Counter(d1) + Counter(d2)
Counter({'A': 9, 'B': 15, 'C': 8, 'E': 2})
Since Counter
is a subclass of dict
, you will likely not want to convert this explicitly to a regular dict
. There are some limitations, namely Counter
works only with positive integers.
I would do it like this:
>>> fst = {'A': 5, 'B': 6, 'C': 8}
>>> snd = {'A': 4, 'B': 9, 'E': 2}
>>> out = {k: fst[k] + snd[k] for k in fst.keys() & snd.keys()}
>>> out.update({k: fst[k] if k in fst else snd[k] for k in fst.keys() ^ snd.keys()})
>>> out
{'A': 9, 'B': 15, 'C': 8, 'E': 2}