Open In App

Python | Merge Python key values to list

Last Updated : 06 Apr, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Sometimes, while working with Python, we might have a problem in which we need to get the values of dictionary from several dictionaries to be encapsulated into one dictionary. This type of problem can be common in domains in which we work with relational data like in web developments. Let’s discuss certain ways in which this problem can be solved. 

Method #1 : Using setdefault() + loop This task can be performed using a nested loop and fetching each element of dictionary and creating a new list to new key or appending the values in case of similar key occurrence. 

Python3




# Python3 code to demonstrate working of
# Merge Python key values to list
# Using setdefault() + loop
 
# Initialize list
test_list = [{'gfg' : 2, 'is' : 4, 'best' : 6},
             {'it' : 5, 'is' : 7, 'best' : 8},
             {'CS' : 10}]
 
# Printing original list
print("The original list is : " + str(test_list))
 
# using setdefault() + loop
# Merge Python key values to list
res = {}
for sub in test_list:
    for key, val in sub.items():
        res.setdefault(key, []).append(val)
 
# printing result
print("The merged values encapsulated dictionary is : " + str(res))


Output : 

The original list is : [{‘is’: 4, ‘gfg’: 2, ‘best’: 6}, {‘it’: 5, ‘is’: 7, ‘best’: 8}, {‘CS’: 10}] The merged values encapsulated dictionary is : {‘is’: [4, 7], ‘it’: [5], ‘gfg’: [2], ‘CS’: [10], ‘best’: [6, 8]}

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

Method #2 : Using list comprehension + dictionary comprehension The combination of above can be used to perform this particular task. This offers a one liner that can be employed for this task. Even though it might be efficient on performance domain. 

Python3




# Python3 code to demonstrate working of
# Merge Python key values to list
# Using list comprehension + dictionary comprehension
 
# Initialize list
test_list = [{'gfg' : 2, 'is' : 4, 'best' : 6},
             {'it' : 5, 'is' : 7, 'best' : 8},
             {'CS' : 10}]
 
# Printing original list
print("The original list is : " + str(test_list))
 
# using list comprehension + dictionary comprehension
# Merge Python key values to list
res = {key: list({sub[key] for sub in test_list if key in sub})
      for key in {key for sub in test_list for key in sub}}
 
# printing result
print("The merged values encapsulated dictionary is : " + str(res))


Output : 

The original list is : [{‘is’: 4, ‘gfg’: 2, ‘best’: 6}, {‘it’: 5, ‘is’: 7, ‘best’: 8}, {‘CS’: 10}] The merged values encapsulated dictionary is : {‘is’: [4, 7], ‘it’: [5], ‘gfg’: [2], ‘CS’: [10], ‘best’: [6, 8]}

The time complexity of this method is O(n^2) where n is the number of elements in the input list of dictionaries. 

The auxiliary space complexity of this method is also O(n^2), because it creates a new set for every key in every dictionary, and a new list for every unique value.

Method 3: Using defaultdict

  • Initialize list
  • Printing original list
  • Using defaultdict Merge Python key values to list
  • Convert defaultdict to a regular dictionary

Python3




from collections import defaultdict
 
# Initialize list
test_list = [{'gfg' : 2, 'is' : 4, 'best' : 6},
             {'it' : 5, 'is' : 7, 'best' : 8},
             {'CS' : 10}]
 
# Printing original list
print("The original list is : " + str(test_list))
 
# using defaultdict
# Merge Python key values to list
res = defaultdict(list)
for sub in test_list:
    for key, val in sub.items():
        res[key].append(val)
 
# convert defaultdict to a regular dictionary
res = dict(res)
 
# printing result
print("The merged values encapsulated dictionary is : " + str(res))


Output

The original list is : [{'gfg': 2, 'is': 4, 'best': 6}, {'it': 5, 'is': 7, 'best': 8}, {'CS': 10}]
The merged values encapsulated dictionary is : {'gfg': [2], 'is': [4, 7], 'best': [6, 8], 'it': [5], 'CS': [10]}

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



Similar Reads

Python - Extract target key from other key values
Sometimes, while working with Python dictionaries, we can have a problem in which we need to extract particular key on basis of other matching record keys when there is exact match. Lets discuss certain ways in which this task can be performed. Method #1: Using loop + conditions This is one of the ways in which this task can be performed. In this,
11 min read
Python - Extract values of Particular Key in Nested Values
Given a dictionary with nested dictionaries as values, extract all the values with of particular key. Input : test_dict = {'Gfg' : {"a" : 7, "b" : 9, "c" : 12}, 'is' : {"a" : 15, "b" : 19, "c" : 20}, 'best' :{"a" : 5, "b" : 10, "c" : 2}}, temp = "b" Output : [9, 10, 19] Explanation : All values of "b" key are extracted. Input : test_dict = {'Gfg' :
4 min read
Python - Assigning Key values to list elements from Value list Dictionary
Given a List of elements, map them with keys of matching values from a value list. Input : test_list = [4, 6, 3, 5, 3], test_dict = {"Gfg" : [5, 3, 6], "is" : [8, 4]} Output : ['is', 'Gfg', 'Gfg', 'Gfg', 'Gfg'] Explanation : 4 is present in "is" key, hence mapped in new list. Input : test_list = [6, 3, 5, 3], test_dict = {"Gfg" : [5, 3, 6], "is" :
7 min read
Python - Extract Key's Value, if Key Present in List and Dictionary
Given a list, dictionary, and a Key K, print the value of K from the dictionary if the key is present in both, the list and the dictionary. Input : test_list = ["Gfg", "is", "Good", "for", "Geeks"], test_dict = {"Gfg" : 5, "Best" : 6}, K = "Gfg" Output : 5 Explanation : "Gfg" is present in list and has value 5 in dictionary. Input : test_list = ["G
11 min read
Python | Merge Tuple String List values to String
Sometimes, while working with records, we can have a problem in which any element of record can be of type string but mistakenly processed as list of characters. This can be a problem while working with a lot of data. Let's discuss certain ways in which this problem can be solved. Method #1: Using list comprehension + join() The combination of abov
6 min read
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. Merge Key Value Lists into Dictionary Python Using zip
8 min read
How to merge many TSV files by common key using Python Pandas?
For data analysis the most important thing is data and we need to prepare it before we can use it for analysis. Sometimes required data can be scattered in multiple files and we need to merge them. In this article, we are going to merge multiple TSV (Tab Separated Values) files with a common key. This can be possible by using the merge method of th
3 min read
Python | Filter dictionary key based on the values in selective list
In Python, sometimes we require to get only some of the dictionary keys and not all. This problem is quite common in web development we require to get only the selective dictionary keys from some given list. Let's discuss certain ways in which this problem can be solved. Method #1: Using list comprehension The list comprehension can be used to solv
9 min read
Python | Get values of particular key in list of dictionaries
Sometimes, we may require a way in which we have to get all the values of the specific key from a list of dictionaries. This kind of problem has a lot of applications in the web development domain in which we sometimes have a JSON and require just to get a single column from records. Let's discuss certain ways in which this problem can be solved. M
10 min read
Python - Convert key-values list to flat dictionary
Sometimes, while working with Python dictionaries, we can have a problem in which we need to flatten dictionary of key-value pair pairing the equal index elements together. This can have utilities in web development and Data Science domain. Lets discuss certain way in which this task can be performed. Convert key-values list to flat dictionary usin
4 min read
Practice Tags :
three90RightbarBannerImg