w3resource

Python: Combine two dictionary adding values for common keys

Python dictionary: Exercise-19 with Solution

Write a Python program to combine two dictionary by adding values for common keys.

Sample Solution:

Python Code:

# Import the 'Counter' class from the 'collections' module.
from collections import Counter

# Create two dictionaries 'd1' and 'd2' with key-value pairs.
d1 = {'a': 100, 'b': 200, 'c': 300}
d2 = {'a': 300, 'b': 200, 'd': 400}

# Use the 'Counter' class to create counter objects for 'd1' and 'd2', which count the occurrences of each key.
# Then, add the counters together to merge the key-value pairs and their counts.
d = Counter(d1) + Counter(d2)

# Print the resulting merged dictionary 'd'.
print(d)

Sample Output:

Counter({'b': 400, 'd': 400, 'a': 400, 'c': 300}) 

Python Code Editor:

Previous: Write a Python program to check a dictionary is empty or not.
Next: Write a Python program to print all unique values in a dictionary.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://198.211.115.131/python-exercises/dictionary/python-data-type-dictionary-exercise-19.php