For example I have two dicts:
Dict A: {'a': 1, 'b': 2, 'c': 3}
Dict B: {'b': 3, 'c': 4, 'd': 5}
I need a pythonic way of 'combining' two dicts such that the result is:
{'a': 1, 'b': 5, 'c': 7, 'd': 5}
That is to say: if a key appears in both dicts, add their values, if it appears in only one dict, keep its value.
For a more generic and extensible way check mergedict. It uses
singledispatch
and can merge values based on its types.Example:
Additionally, please note
a.update( b )
is 2x faster thana + b
The above solutions are great for the scenario where you have a small number of
Counter
s. If you have a big list of them though, something like this is much nicer:The above solution is essentially summing the
Counter
s by:This does the same thing but I think it always helps to see what it is effectively doing underneath.
Merging three dicts a,b,c in a single line without any other modules or libs
If we have the three dicts
Merge all with a single line and return a dict object using
Returning
This is a simple solution for merging two dictionaries where
+=
can be applied to the values, it has to iterate over a dictionary only once, I'm surprised no one has suggested this