Javatpoint Logo
Javatpoint Logo

Write the Python Program to Combine Two Dictionary Values for Common Keys

This tutorial will write a Python program to combine the two dictionaries with the common keys. Dictionary is a Python data structure that stores the data in the key-value pair. Each key should be immutable and unique in the dictionary. Let's understand the above problem statement.

Problem Statement

We need to merge the given dictionary and create the new dictionaries based on the common keys. Let's see the following example.

Example -

Let's understand the following solutions.

Solution

We will solve this problem using the Counter Module. Let's see the following code.

Example -

Output:

The new dict is: Counter({'a': 400, 'b': 400, 'd': 400, 'c': 300})

Explanation -

We have imported the Counter function from the collections module in the above code. Then, we assigned the two dictionaries and called the Counter() function on dict1 and dict2. This method finds the common keys and sums their values. In the dict1, the key a has a value of 100, and in dict2, a has a value of 200. So the Counter() method added both values and returned a new value of 400. Hence we created a new dictionary.

Example - 2:

Output:

The new dict is: {'a': 400, 'b': 400, 'd': 400, 'c': 300}

Explanation -

In the above code, we initialized the dictionaries and the dict2 in the new_dict. Then, we run for loop using the items() method to the dict2. Then, we checked if the key exists in dict1; if true, then add it with the value to the dict1; else assign as a key of new_dict.

Example - 3:

Output:

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

Example - 4

Output:

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

Conclusion

This programming question can be asked in the technical interview round. This tutorial included the solution of the problem along with the explanation.







Youtube For Videos Join Our Youtube Channel: Join Now

Feedback


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA