Sometimes, while working with dictionaries, we can have a problem in which we have many dictionaries and we are required to merge like keys. This problem seems common, but complex is if the values of keys are list and we need to add elements to list of like keys. Let’s discuss way in which this problem can be solved.
Method : Using list comprehension + items() This problem can be solved using list comprehension that can be used to merge the list content and also the items method which can be employed to get the dictionary keys and values.
Python3
# Python3 code to demonstrate working of # List value merge in dictionary # Using items() + list comprehension # initializing dictionaries test_dict1 = { 'Gfg' : [ 1 , 2 , 3 ], 'for' : [ 2 , 4 ], 'CS' : [ 7 , 8 ]} test_dict2 = { 'Gfg' : [ 10 , 11 ], 'for' : [ 5 ], 'CS' : [ 0 , 18 ]} # printing original dictionaries print ("The original dictionary 1 is : " + str (test_dict1)) print ("The original dictionary 2 is : " + str (test_dict2)) # Using items() + list comprehension # List value merge in dictionary res = {key: value + test_dict2[key] for key, value in test_dict1.items()} # printing result print ("The merged dictionary is : " + str (res)) |
The original dictionary 1 is : {‘for’: [2, 4], ‘CS’: [7, 8], ‘Gfg’: [1, 2, 3]} The original dictionary 2 is : {‘for’: [5], ‘CS’: [0, 18], ‘Gfg’: [10, 11]} The merged dictionary is : {‘for’: [2, 4, 5], ‘CS’: [7, 8, 0, 18], ‘Gfg’: [1, 2, 3, 10, 11]}
Alternative Approach
This problem can also be solved using the set() and & method can be used to add the values of one dictionary to the other.
Python3
# Python3 code to demonstrate working of # List value merge in dictionary # Using update() # initializing dictionaries test_dict1 = { 'Gfg' : [ 1 , 2 , 3 ], 'for' : [ 2 , 4 ], 'CS' : [ 7 , 8 ]} test_dict2 = { 'Gfg' : [ 10 , 11 ], 'for' : [ 5 ], 'CS' : [ 0 , 18 ]} # printing original dictionaries print ( "The original dictionary 1 is : " + str (test_dict1)) print ( "The original dictionary 2 is : " + str (test_dict2)) # Using update() # List value merge in dictionary res = {key: test_dict1[key] + test_dict2[key] for key in set (test_dict1) & set (test_dict2)} # printing result print ( "The merged dictionary is : " + str (res)) #This code is contributed by Edula Vinay Kumar Reddy |
The original dictionary 1 is : {'Gfg': [1, 2, 3], 'for': [2, 4], 'CS': [7, 8]} The original dictionary 2 is : {'Gfg': [10, 11], 'for': [5], 'CS': [0, 18]} The merged dictionary is : {'for': [2, 4, 5], 'CS': [7, 8, 0, 18], 'Gfg': [1, 2, 3, 10, 11]}
Time Complexity : O(n)
Auxiliary Space : O(n)
Method #3: Using the defaultdict class from the collections module
Step-by-Step Algorithm:
- Import the defaultdict class from the collections module
- Define the dictionaries to merge
- Create a defaultdict to store the merged values
- Loop through the keys of both dictionaries and merge their values
- Add the values of both dictionaries to the merged dictionary using defaultdict
- Convert the defaultdict to a normal dictionary using dict() function
- Print the original dictionaries and the merged dictionary
Python3
# Import the defaultdict class from the collections module from collections import defaultdict # Define the dictionaries to merge dict1 = { 'for' : [ 2 , 4 ], 'CS' : [ 7 , 8 ], 'Gfg' : [ 1 , 2 , 3 ]} dict2 = { 'for' : [ 5 ], 'CS' : [ 0 , 18 ], 'Gfg' : [ 10 , 11 ]} # Create a defaultdict to store the merged values merged_dict = defaultdict( list ) # Loop through the keys of both dictionaries and merge their values for key in dict1.keys() | dict2.keys(): merged_dict[key] = dict1.get(key, []) + dict2.get(key, []) # Print the original dictionaries and the merged dictionary print ( "The original dictionary 1 is :" , dict1) print ( "The original dictionary 2 is :" , dict2) print ( "The merged dictionary is :" , dict (merged_dict)) |
The original dictionary 1 is : {'for': [2, 4], 'CS': [7, 8], 'Gfg': [1, 2, 3]} The original dictionary 2 is : {'for': [5], 'CS': [0, 18], 'Gfg': [10, 11]} The merged dictionary is : {'Gfg': [1, 2, 3, 10, 11], 'for': [2, 4, 5], 'CS': [7, 8, 0, 18]}
Time Complexity: O(n), where n is the size of the merged dictionary.
Auxiliary Space: O(m+n), where m and n are the sizes of the two dictionaries to be merged. The additional space is used to store the merged dictionary.
Method #4: Using itertools and chain():
- Import the itertools module to use the chain() function.
- Initialize two dictionaries with keys and values as lists.
- Print the original dictionaries.
- Create an empty dictionary to store the merged values.
- Use the union() method to find the set of keys that are present in both dictionaries.
- Use a loop to iterate over the set of keys and set the key-value pair in the merged dictionary using the chain() function to combine the values from both dictionaries for the corresponding key.
- Print the merged dictionary.
Python3
from itertools import chain # initializing dictionaries test_dict1 = { 'Gfg' : [ 1 , 2 , 3 ], 'for' : [ 2 , 4 ], 'CS' : [ 7 , 8 ]} test_dict2 = { 'Gfg' : [ 10 , 11 ], 'for' : [ 5 ], 'CS' : [ 0 , 18 ]} # printing original dictionaries print ( "The original dictionary 1 is : " + str (test_dict1)) print ( "The original dictionary 2 is : " + str (test_dict2)) # Using itertools and chain() # List value merge in dictionary res = {} for key in set (test_dict1).union(test_dict2): res[key] = list (chain(test_dict1.get(key, []), test_dict2.get(key, []))) # printing result print ( "The merged dictionary is : " + str (res)) |
The original dictionary 1 is : {'Gfg': [1, 2, 3], 'for': [2, 4], 'CS': [7, 8]} The original dictionary 2 is : {'Gfg': [10, 11], 'for': [5], 'CS': [0, 18]} The merged dictionary is : {'Gfg': [1, 2, 3, 10, 11], 'for': [2, 4, 5], 'CS': [7, 8, 0, 18]}
The time complexity is O(n), where n is the total number of elements in both dictionaries.
The space complexity of this approach is O(n), where n is the total number of elements in both dictionaries.