Open In App

Python | Combine the values of two dictionaries having same key

Dictionary is a collection which is unordered, changeable and indexed. In Python, dictionaries are written with curly brackets, and they have keys and values. It is widely used in day to day programming, web development, and machine learning. Combining dictionaries is very common task in operations of dictionary. Let’s see how to combine the values of two dictionaries having same key. 

Method #1: Using Counter 



Counter is a special subclass of dictionary that performs acts same as dictionary in most cases. 

Step-by-step approach:



Below is the implementation of the above approach:




# Python code to demonstrate combining
# two dictionaries having same key
 
from collections import Counter
 
# initialising dictionaries
ini_dictionary1 = Counter({'nikhil': 1, 'akash' : 5,
                    'manjeet' : 10, 'akshat' : 15})
ini_dictionary2 = Counter({'akash' : 7, 'akshat' : 5,
                                        'm' : 15})
 
# printing initial dictionaries
print ("initial 1st dictionary", str(ini_dictionary1))
print ("initial 2nd dictionary", str(ini_dictionary2))
 
# combining dictionaries
# using Counter
final_dictionary = ini_dictionary1 + ini_dictionary2
 
# printing final result
print ("final dictionary", str(final_dictionary))

Output
initial 1st dictionary Counter({'akshat': 15, 'manjeet': 10, 'akash': 5, 'nikhil': 1})
initial 2nd dictionary Counter({'m': 15, 'akash': 7, 'akshat': 5})
final dictionary Counter({'akshat': 20, 'm': 15, 'akash': 12, 'manjeet': 10, 'nikhil': 1})

Time Complexity: O(n)
Auxiliary Space: O(1)

Method #2: Using dict() and items This method is for Python version 2. 

Step-by-step approach:

Below is the implementation of the above approach:




# Python code to demonstrate combining
# two dictionaries having same key
 
 
# initialising dictionaries
ini_dictionary1 = {'nikhil': 1, 'akash' : 5,
            'manjeet' : 10, 'akshat' : 15}
ini_dictionary2 = {'akash' : 7, 'akshat' : 5,
                                    'm' : 15}
 
# printing initial dictionaries
print ("initial 1st dictionary", str(ini_dictionary1))
print ("initial 2nd dictionary", str(ini_dictionary2))
 
# combining dictionaries
# using dict() and items()
final_dictionary = dict(ini_dictionary1.items() + ini_dictionary2.items() +
                    [(k, ini_dictionary1[k] + ini_dictionary2[k])
                    for k in set(ini_dictionary2)
                    & set(ini_dictionary1)])
 
# printing final result
print ("final dictionary", str(final_dictionary))

Output
('initial 1st dictionary', "{'manjeet': 10, 'nikhil': 1, 'akshat': 15, 'akash': 5}")
('initial 2nd dictionary', "{'m': 15, 'akshat': 5, 'akash': 7}")
('final dictionary', "{'nikhil': 1, 'm': 15, 'manjeet': 10, 'akshat': 20, 'akash': 12}")

Time complexity: O(n), where n is the number of elements in both dictionaries.
Auxiliary space: O(n), where n is the size of the final dictionary created by combining both dictionaries.

Method #3: Using dict comprehension and set 




# Python code to demonstrate combining
# two dictionaries having same key
 
# initialising dictionaries
ini_dictionary1 = {'nikhil': 1, 'akash' : 5,
            'manjeet' : 10, 'akshat' : 15}
ini_dictionary2 = {'akash' : 7, 'akshat' : 5,
                                    'm' : 15}
 
# printing initial dictionaries
print ("initial 1st dictionary", str(ini_dictionary1))
print ("initial 2nd dictionary", str(ini_dictionary2))
 
# combining dictionaries
# using dict comprehension and set
final_dictionary = {x: ini_dictionary1.get(x, 0) + ini_dictionary2.get(x, 0)
                    for x in set(ini_dictionary1).union(ini_dictionary2)}
 
# printing final result
print ("final dictionary", str(final_dictionary))

Output
initial 1st dictionary {'nikhil': 1, 'akash': 5, 'manjeet': 10, 'akshat': 15}
initial 2nd dictionary {'akash': 7, 'akshat': 5, 'm': 15}
final dictionary {'m': 15, 'manjeet': 10, 'akshat': 20, 'nikhil': 1, 'akash': 12}

Time complexity: O(n), where n is the total number of key-value pairs in both dictionaries.
Auxiliary space: O(n), where n is the total number of key-value pairs in both dictionaries

Method #4: Using dict() and for loop

Combine two dictionaries with the same keys using a for loop and the dict() constructor to create a new dictionary. 




# initialising dictionaries
ini_dictionary1 = {'nikhil': 1, 'akash' : 5, 'manjeet' : 10, 'akshat' : 15}
ini_dictionary2 = {'akash' : 7, 'akshat' : 5, 'm' : 15}
 
# combining dictionaries using a for loop and dict() constructor
final_dictionary = {}
for key in ini_dictionary1:
    final_dictionary[key] = ini_dictionary1[key] + ini_dictionary2.get(key, 0)
for key in ini_dictionary2:
    if key not in final_dictionary:
        final_dictionary[key] = ini_dictionary2[key]
 
# printing final result
print("final dictionary", str(final_dictionary))

Output
final dictionary {'nikhil': 1, 'akash': 12, 'manjeet': 10, 'akshat': 20, 'm': 15}

Time complexity: O(n), where n is the total number of key-value pairs in both dictionaries.
Auxiliary space: O(n), where n is the total number of key-value pairs in both dictionaries

Method #5:  use the update() method. 

Step-by-step approach:

Below is the implementation of the above approach:




# initialising dictionaries
ini_dictionary1 = {'nikhil': 1, 'akash': 5, 'manjeet': 10, 'akshat': 15}
ini_dictionary2 = {'akash': 7, 'akshat': 5, 'm': 15}
 
# combining dictionaries using update() method
final_dictionary = ini_dictionary1.copy()
final_dictionary.update(ini_dictionary2)
 
# printing final result
print("final dictionary", str(final_dictionary))

Output
final dictionary {'nikhil': 1, 'akash': 7, 'manjeet': 10, 'akshat': 5, 'm': 15}

Time complexity: O(n+m), where n and m are the sizes of the two dictionaries. 
Auxiliary space: O(n), where n is the size of the first dictionary.

Method #6: Using the ** operator

Step-by-step approach:

Below is the implementation of the above approach:




# initializing dictionaries
ini_dictionary1 = {'nikhil': 1, 'akash': 5, 'manjeet': 10, 'akshat': 15}
ini_dictionary2 = {'akash': 7, 'akshat': 5, 'm': 15}
 
# combining dictionaries using the ** operator
final_dictionary = {**ini_dictionary1, **ini_dictionary2}
 
# printing final result
print("final dictionary", str(final_dictionary))

Output
final dictionary {'nikhil': 1, 'akash': 7, 'manjeet': 10, 'akshat': 5, 'm': 15}

Time complexity: O(n), where n is the total number of elements in both dictionaries.
Auxiliary space: O(n), where n is the total number of elements in both dictionaries. 

Method #7: Using Merge Operator

Step-by-Step Approach:




# initialising dictionaries
ini_dictionary1 = {'nikhil': 1, 'akash' : 5, 'manjeet' : 10, 'akshat' : 15}
ini_dictionary2 = {'akash' : 7, 'akshat' : 5, 'm' : 15}
 
# printing initial dictionaries
print ("initial 1st dictionary", str(ini_dictionary1))
print ("initial 2nd dictionary", str(ini_dictionary2))
 
# combining dictionaries using merge operator
merged_dict = {**ini_dictionary1, **ini_dictionary2}
final_dict = {}
for key, value in merged_dict.items():
    final_dict[key] = final_dict.get(key, 0) + value
 
# printing final result
print ("final dictionary", str(final_dict))

Output
initial 1st dictionary {'nikhil': 1, 'akash': 5, 'manjeet': 10, 'akshat': 15}
initial 2nd dictionary {'akash': 7, 'akshat': 5, 'm': 15}
final dictionary {'nikhil': 1, 'akash': 7, 'manjeet': 10, 'akshat': 5, 'm': 15}

Time Complexity: O(m+n), where m and n are the number of items in the two dictionaries.
Auxiliary Space: O(m+n), where m and n are the number of items in the two dictionaries.


Article Tags :