Back to the page

In the print window, choose “Save as PDF”.

doubtly doubtly.in

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

Python · Updated 27 Jan 2024 · Read online: www.doubtly.in/write-a-python-program-to-combine-two-dictionaries-by-adding-values-for-common-keys/

Write a Python program to combine two dictionaries by adding values for common keys. 
d1 = {‘a’: 100, ‘b’: 200, ‘c’:300}
d2 = {‘a’: 300, ‘b’: 200, ‘d’:400}
Sample output: Counter({‘a’: 400, ‘b’: 400, ‘d’: 400, ‘c’: 300})

from collections import Counter

def combine_dictionaries(d1, d2):
    counter_d1 = Counter(d1)
    counter_d2 = Counter(d2)

    combined_counter = counter_d1 + counter_d2

    return combined_counter

# Example dictionaries
d1 = {'a': 100, 'b': 200, 'c': 300}
d2 = {'a': 300, 'b': 200, 'd': 400}

# Combine dictionaries
result = combine_dictionaries(d1, d2)

# Print the result
print(result)

Practise this on Doubtly (free)