Python | List value merge in dictionary
Last Updated :
30 Apr, 2023
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))
Output :
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
OutputThe 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))
OutputThe 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))
OutputThe 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.
Similar Reads
Merge Key Value Lists into Dictionary Python
Sometimes, while working with lists, we can come forward with a problem in which we need to perform the merge function in which we have the key list and need to create dictionary mapping keys with corresponding value in other list. Let's discuss certain ways in which this task can be performed. Merg
8 min read
Inverse Dictionary Values List - Python
We are given a dictionary and the task is to create a new dictionary where each element of the value lists becomes a key and the original keys are grouped as lists of values for these new keys.For example: dict = {1: [2, 3], 2: [3], 3: [1]} then output will be {2: [1], 3: [1, 2], 1: [3]} Using defau
2 min read
Python Iterate Dictionary Key, Value
In Python, a Dictionary is a data structure that stores the data in the form of key-value pairs. It is a mutable (which means once created we modify or update its value later on) and unordered data structure in Python. There is a thing to keep in mind while creating a dictionary every key in the dic
3 min read
Python - Print dictionary of list values
In this article, we will explore various ways on How to Print Dictionary in Python of list values. A dictionary of list values means a dictionary contains values as a list of dictionaries in Python. Example: {'key1': [{'key1': value,......,'key n': value}........{'key1': value,......,'key n': value}
4 min read
Python | Grouping list values into dictionary
Sometimes, while working with data, we can be encountered a situation in which we have a list of lists and we need to group its 2nd index with the common initial element in lists. Let's discuss ways in which this problem can be solved. Method 1: Using defaultdict() + loop + dict() The defaultdict ca
7 min read
Python - Common items Dictionary Value List
The functionality of union has been discussed many times. But sometimes, we can have a more complex container, in which we need to check for the intersection of lists which are in form of keys of dictionary. Letâs discuss certain ways to solve this type of problem. Method #1: Using Loops Using loops
10 min read
Python - Append Multitype Values in Dictionary
There are cases where we may want to append multiple types of values, such as integers, strings or lists to a single dictionary key. For example, if we are creating a dictionary to store multiple types of data under the same key, such as user details (e.g., age, address, and hobbies), we need to han
2 min read
Get List of Values From Dictionary - Python
We are given a dictionary and our task is to extract all the values from it and store them in a list. For example, if the dictionary is d = {'a': 1, 'b': 2, 'c': 3}, then the output would be [1, 2, 3]. Using dict.values()We can use dict.values() along with the list() function to get the list. Here,
2 min read
Python | Extract filtered Dictionary Values
While working with Python dictionaries, there can be cases in which we are just concerned about getting the filtered values list and donât care about keys. This is yet another essential utility and solution to it should be known and discussed. Letâs perform this task through certain methods. Method
4 min read
Python - Dictionary Values Division
Sometimes, while working with dictionaries, we might have utility problem in which we need to perform elementary operation among the common keys of dictionaries. This can be extended to any operation to be performed. Letâs discuss division of like key values and ways to solve it in this article. Met
5 min read