Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any pythonic way to combine two dicts (adding values for keys that appear in both)?

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.

like image 226
Derrick Zhang Avatar asked Jun 13 '12 09:06

Derrick Zhang


People also ask

Can you concatenate Dicts in Python?

In the latest update of python now we can use “|” operator to merge two dictionaries. It is a very convenient method to merge dictionaries.

Can Dicts have same keys?

The straight answer is NO. You can not have duplicate keys in a dictionary in Python.

Can a dictionary have two key-value pairs with the same key?

No, each key in a dictionary should be unique. You can't have two keys with the same value. Attempting to use the same key again will just overwrite the previous value stored.


1 Answers

Use collections.Counter:

>>> from collections import Counter >>> A = Counter({'a':1, 'b':2, 'c':3}) >>> B = Counter({'b':3, 'c':4, 'd':5}) >>> A + B Counter({'c': 7, 'b': 5, 'd': 5, 'a': 1}) 

Counters are basically a subclass of dict, so you can still do everything else with them you'd normally do with that type, such as iterate over their keys and values.

like image 128
Martijn Pieters Avatar answered Sep 21 '22 23:09

Martijn Pieters