Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (47.6k points)

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.

1 Answer

0 votes
by (106k points)

For combining two dictionaries you can use the collections.Counte. The 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.

>>> from collections import Counter

>>> A = Counter({'a':1, 'b':2, 'c':3})

>>> B = Counter({'b':3, 'c':4, 'd':5})

>>> A + B

image

Browse Categories

...