KnowledgeBoat Logo

Computer Science

Write a Python program to combine two dictionaries 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, 'c': 300, 'd': 400})

Python

Python Dictionaries

3 Likes

Answer

d1 = {'a': 100, 'b': 200, 'c': 300}
d2 = {'a': 300, 'b': 200, 'd': 400}
combined_dict = {}
for key, value in d1.items():
    combined_dict[key] = value
for key, value in d2.items():
    if key in combined_dict:
        combined_dict[key] += value
    else:
        combined_dict[key] = value

print("Combined dictionary with added values for common keys:", combined_dict)

Output

Combined dictionary with added values for common keys: {'a': 400, 'b': 400, 'c': 300, 'd': 400}

Answered By

1 Like


Related Questions