Open In App

Python | Segregating key’s value in list of dictionaries

Improve
Improve
Like Article
Like
Save
Share
Report

While working with dictionaries, we may encounter problems in which we need to segregate all the similar keys’ values together. This kind of problem can occur in web development domain while working with databases. Let’s discuss certain ways in which this problem can be solved. 

Method #1: Using generator expression 

A generator expression can be used to perform this particular task. In this, we take one key at a time and check for the matching keys in all dictionaries. The drawback is that we need to know the key’s in advance. 

Python3




# Python3 code to demonstrate working of
# Segregating key's value in list of dictionaries
# Using generator expression
 
# Initialize list
test_list = [{'gfg' : 1, 'best' : 2}, {'gfg' : 4, 'best': 5}]
 
# printing original list
print("The original list : " + str(test_list))
 
# Using generator expression
# Segregating key's value in list of dictionaries
res = [tuple(sub["gfg"] for sub in test_list),
    tuple(sub["best"] for sub in test_list)]
     
# printing result
print("Segregated values of keys are : " + str(res))


Output

The original list : [{'gfg': 1, 'best': 2}, {'gfg': 4, 'best': 5}]
Segregated values of keys are : [(1, 4), (2, 5)]

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

Method #2: Using zip() + map() + values()

The combination of above functions can also perform the similar task in one line. In this, values() is used to extract values, map() is used to link individual keys with one other and finally zip() joins their corresponding values to single tuple. 

Python3




# Python3 code to demonstrate working of
# Segregating key's value in list of dictionaries
# Using zip() + map() + values()
 
# Initialize list
test_list = [{'gfg': 1, 'best': 2}, {'gfg': 4, 'best': 5}]
 
# printing original list
print("The original list : " + str(test_list))
 
# Using zip() + map() + values()
# Segregating key's value in list of dictionaries
res = list(zip(*map(dict.values, test_list)))
 
# printing result
print("Segregated values of keys are : " + str(res))


Output

The original list : [{'gfg': 1, 'best': 2}, {'gfg': 4, 'best': 5}]
Segregated values of keys are : [(1, 4), (2, 5)]

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

Method #3: Using list comprehension

Use a list comprehension to iterate over the list of dictionaries and extract the values of the keys we’re interested in. We then convert the resulting generator expressions to tuples using the tuple() function and store them in a tuple variable res.

Step-by-step approach:

  1. Define a list of dictionaries test_list with two dictionaries, each containing the keys ‘gfg’ and ‘best’ with their respective values.
  2. Print the original list.
  3. Using list comprehension, segregate the values of ‘gfg’ and ‘best’ keys from the list of dictionaries. The list comprehension creates two generator expressions, one for ‘gfg’ and one for ‘best’, by iterating over each dictionary in the test_list and retrieving the value corresponding to the key.
  4. Convert the generator expressions into tuples using the map() function and the tuple() constructor. The map() function applies the tuple() constructor to each generator expression and returns a map object. The tuple() constructor then converts each map object into a tuple.
  5. Print the resulting tuple of tuples that contains the segregated values of ‘gfg’ and ‘best’ keys.
  6. End of the program.

Python3




# Python3 code to demonstrate working of
# Segregating key's value in list of dictionaries
# Using list comprehension
 
# Initialize list
test_list = [{'gfg': 1, 'best': 2}, {'gfg': 4, 'best': 5}]
 
# printing original list
print("The original list : " + str(test_list))
 
# Using list comprehension
# Segregating key's value in list of dictionaries
res = [(sub['gfg'] for sub in test_list), (sub['best'] for sub in test_list)]
 
# converting generator expression to tuple
res = tuple(map(tuple, res))
 
# printing result
print("Segregated values of keys are : " + str(res))


Output

The original list : [{'gfg': 1, 'best': 2}, {'gfg': 4, 'best': 5}]
Segregated values of keys are : ((1, 4), (2, 5))

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

Method #4: Using a loop

We take a list of dictionaries test_list and a list of keys keys. It then loops through each key and retrieves the corresponding value from each dictionary in test_list. The values are stored in a tuple and appended to a list res

Python3




test_list = [{'gfg': 1, 'best': 2}, {'gfg': 4, 'best': 5}]
keys = ['gfg', 'best']
 
# printing original list
print("The original list : " + str(test_list))
 
res = []
for key in keys:
    values = []
    for d in test_list:
        values.append(d[key])
    res.append(tuple(values))
 
# printing the result
print("Segregated values of keys are : " + str(tuple(res)))


Output

The original list : [{'gfg': 1, 'best': 2}, {'gfg': 4, 'best': 5}]
Segregated values of keys are : ((1, 4), (2, 5))

Time Complexity: O(nk), where n is the number of dictionaries in the input list and k is the number of keys being segregated.
Auxiliary Space: O(nk), since we’re storing a tuple of values for each key.

Method #6: Using pandas library

This method first converts the list of dictionaries into a pandas DataFrame using the pd.DataFrame() function. Then, it extracts the values of the ‘gfg’ and ‘best’ columns using the column names as keys, and converts them into tuples using the tuple() function. Finally, it assigns these tuples to the variable res.

Python3




import pandas as pd
 
test_list = [{'gfg' : 1, 'best' : 2}, {'gfg' : 4, 'best': 5}]
df = pd.DataFrame(test_list)
res = tuple(df['gfg']), tuple(df['best'])
 
print("Segregated values of keys are : " + str(res))


OUTPUT:

Segregated values of keys are : ((1, 4), (2, 5))

Time complexity; O(n), where n is the number of dictionaries in the list.
Auxiliary space: O(n), as it creates a DataFrame object that contains the data from the list of dictionaries.

Method #6: Using dictionary comprehension

Step-by-step approach:

  1. Initialize the list of dictionaries.
  2. Using dictionary comprehension, segregate the values of keys in the list of dictionaries. Here, k is the key of the dictionary, and test_list[0] is used to access the keys of the first dictionary in the list. The values of each key are extracted from the corresponding dictionaries using a tuple comprehension.
  3. Convert the dictionary values to a list using the list() function and access the values using the values() method of the dictionary.

Python3




# Initialize list
test_list = [{'gfg' : 1, 'best' : 2}, {'gfg' : 4, 'best': 5}]
 
# Using dictionary comprehension
# Segregating key's value in list of dictionaries
res = {k: tuple(sub[k] for sub in test_list) for k in test_list[0]}
 
# printing result
print("Segregated values of keys are : " + str(list(res.values())))


Output

Segregated values of keys are : [(1, 4), (2, 5)]

Time complexity: O(n*k), where n is the number of dictionaries in the list and k is the number of keys in each dictionary.
Auxiliary space: O(k), where k is the number of keys in each dictionary.



Last Updated : 04 Apr, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads