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)

Related Articles

Responses

Your email address will not be published. Required fields are marked *