Intellipaat Back

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

I have two dictionaries and I need to combine them. I need to sum the values of similar keys and the different keys leave them without sum.

These are the two dictionaries:

d1 = {'a': 100, 'b': 200, 'c':300}

d2 = {'a': 300, 'b': 200, 'd':400}

The expected results:

d3= {'b': 400, 'd': 400, 'a': 400, 'c': 300}

I have successfully made the sum and added them to this third dictionary, but I couldn't know, how to add the different values.

My try

d1 = {'a': 100, 'b': 200, 'c':300}

d2 = {'a': 300, 'b': 200, 'd':400}

d3 = {}

for i, j in d1.items():

    for x, y in d2.items():

        if i == x:

            d3[i]=(j+y)

print(d3)

My results = {'a': 400, 'b': 400}

2 Answers

0 votes
by (25.1k points)

You can do it like this:

d1 = {'a': 100, 'b': 200, 'c':300}

d2 = {'a': 300, 'b': 200, 'd':400}

d3 = dict(d1) # don't do `d3=d1`, you need to make a copy

d3.update(d2) 

for i, j in d1.items():

    for x, y in d2.items():

        if i == x:

            d3[i]=(j+y)

print(d3)

If you wish to learn more about Python, visit the Python tutorial and Python Certification course by Intellipaat. 

0 votes
ago by (3.1k points)

You can merge two dictionaries in Python with these simple steps:

1. Iteration over the second dictionary, for every key-value pair of the second dictionary you should see if the key exists in the first dictionary.

2.If key is same in both dictionaries, then add the sum of both values.

3.If the given key is unique add it to the combined dictionary.

Example:

dict1 = {‘keya': 100, 'keyb': 200, 'keyc': 300}

dict2 = {'b': 150, 'c': 250, 'd': 400}

combined_dict = dict1.copy()

for key, value in dict2.items():

    if key in combined_dict:

        combined_dict[key] += value

    else:

        combined_dict[key] = value

print(combined_dict)

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...