Open In App
Related Articles

Python | Get values of particular key in list of dictionaries

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Share
Report issue
Report

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. 

Method #1: Using list comprehension 

Using list comprehension is quite straight forward method to perform this particular task. In this, we just iterate over the list of dictionaries for the desired value. 

Step-by-step approach:

  • Use list comprehension to get the values of the key ‘gfg’ from the list of dictionaries. The list comprehension iterates through each dictionary in the list, and for each dictionary, it retrieves the value of the key ‘gfg’. The result is stored in a new list, ‘res’.
  • The resulting list ‘res’ is printed using the print() function, which displays the values corresponding to the key ‘gfg’.

Python3

# Python3 code to demonstrate working of
# Get values of particular key in list of dictionaries
# Using list comprehension
 
# initializing list
test_list = [{'gfg' : 1, 'is' : 2, 'good' : 3},
             {'gfg' : 2}, {'best' : 3, 'gfg' : 4}]
 
# printing original list
print("The original list is : " + str(test_list))
 
# Using list comprehension
# Get values of particular key in list of dictionaries
res = [ sub['gfg'] for sub in test_list ]
 
# printing result
print("The values corresponding to key : " + str(res))

                    

Output
The original list is : [{'gfg': 1, 'is': 2, 'good': 3}, {'gfg': 2}, {'best': 3, 'gfg': 4}]
The values corresponding to key : [1, 2, 4]

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

Method #2 : Using map() + itemgetter() 

This problem can also be solved using another technique using map() and itemgetter(). In this, map is used to link the value to all the dictionary keys and itemgetter gets the desired key. 

Python3

# Python3 code to demonstrate working of
# Get values of particular key in list of dictionaries
# Using map() + itemgetter()
from operator import itemgetter
 
# initializing list
test_list = [{'gfg' : 1, 'is' : 2, 'good' : 3},
             {'gfg' : 2}, {'best' : 3, 'gfg' : 4}]
 
# printing original list
print("The original list is : " + str(test_list))
 
# Using map() + itemgetter()
# Get values of particular key in list of dictionaries
res = list(map(itemgetter('gfg'), test_list))
 
# printing result
print("The values corresponding to key : " + str(res))

                    

Output
The original list is : [{'gfg': 1, 'is': 2, 'good': 3}, {'gfg': 2}, {'best': 3, 'gfg': 4}]
The values corresponding to key : [1, 2, 4]

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

Method #3: Using Python Dictionary

Python3

# Python3 code to demonstrate working of
# Get values of particular key in list of dictionaries
 
res = {}
 
# initializing list
test_list = [{'gfg': 1, 'is': 2, 'good': 3},
             {'gfg': 2}, {'best': 3, 'gfg': 4}]
 
# printing original list
print("The original list is : " + str(test_list))
 
for i in test_list:
    for j in i:
        if j in res.keys():
            res[j].append(i[j])
        else:
            res[j] = [i[j]]
 
# printing result
print("The values corresponding to key : " + str(res['gfg']))

                    

Output
The original list is : [{'gfg': 1, 'is': 2, 'good': 3}, {'gfg': 2}, {'best': 3, 'gfg': 4}]
The values corresponding to key : [1, 2, 4]

Time complexity: O(NM), where N is the length of the input list test_list and M is the maximum number of keys in a dictionary in the input list. 
Space complexity: O(N*M), where N is the length of the input list test_list and M is the maximum number of keys in a dictionary in the input list. 

Method #4: Using list comprehension and .get() method

Note: This approach also considers the case where the key does not exists.

Another approach to getting the values of a specific key in a list of dictionaries is to use list comprehension and the .get() method. The .get() method allows you to specify a default value to return if the key is not found in the dictionary. This can be useful for avoiding KeyError exceptions when working with a list of dictionaries that may not contain the same keys.

Python3

# Python3 code to demonstrate working of
# Get values of particular key in list of dictionaries
# Using list comprehension and .get() method
 
# initializing list
test_list = [{'gfg': 1, 'is': 2, 'good': 3},
             {'gfg': 2}, {'best': 3, 'gfg': 4}]
 
# printing original list
print("The original list is : " + str(test_list))
 
# Using list comprehension and .get() method
# Get values of particular key in list of dictionaries
res = [d.get('gfg', None) for d in test_list]
 
# printing result
print("The values corresponding to key : " + str(res))
# This code is contributed by Edula Vinay Kumar Reddy

                    

Output
The original list is : [{'gfg': 1, 'is': 2, 'good': 3}, {'gfg': 2}, {'best': 3, 'gfg': 4}]
The values corresponding to key : [1, 2, 4]

Time complexity: O(n) where n is the number of dictionaries in the list.
Auxiliary Space: O(n) where n is the number of values returned in the result list.

Method #5: Using Recursive method.

Step-by-step approach:

  • Define a function that takes a list of dictionaries (lst) and a key to search for (key) as input.
  • Base case: If the list is empty, return an empty list.
  • Get the first dictionary in the list.
  • Check if the key is in the first dictionary.
  • If the key is in the dictionary, add the value to the result list.
  • If the key is not in the dictionary, the result list is empty.
  • Recursively call the function on the rest of the list.
  • Append the result of the recursive call to the current result list.
  • Return the result list.

Python3

def get_values(lst, key):
    # base case: if the list is empty, return an empty list
    if not lst:
        return []
 
    # get the first dictionary in the list
    first_dict = lst[0]
 
    # check if the key is in the first dictionary
    if key in first_dict:
        # if the key is in the dictionary, add the value to the result list
        result = [first_dict[key]]
    else:
        # if the key is not in the dictionary, the result list is empty
        result = []
 
    # recursively call the function on the rest of the list
    result += get_values(lst[1:], key)
 
    return result
 
 
# initializing list
test_list = [{'gfg': 1, 'is': 2, 'good': 3},
             {'gfg': 2}, {'best': 3, 'gfg': 4}]
 
# printing original list
print("The original list is : " + str(test_list))
 
# get values of 'gfg' key using recursive method
res = get_values(test_list, 'gfg')
 
# printing result
print("The values corresponding to key : " + str(res))
# this code contributed by tvsk

                    

Output
The original list is : [{'gfg': 1, 'is': 2, 'good': 3}, {'gfg': 2}, {'best': 3, 'gfg': 4}]
The values corresponding to key : [1, 2, 4]

Time Complexity: O(n*m), where n is the length of the list and m is the average number of keys in each dictionary. In the worst case, the function has to check every dictionary in the list for the key, resulting in O(n) time complexity. Additionally, the function has to access the value of the key in each dictionary, which takes O(m) time on average.
Auxiliary Space: O(n), where n is the length of the list. This is because the function creates a result list that is as long as the input list. Additionally, the function uses recursion, which creates a new stack frame for each call, resulting in O(n) space complexity.

Method 6:  Using a for loop and checking each dictionary in the list for the given key. 

Step-by-step approach:

  • Define a function named get_values that takes two arguments – a list lst and a string key.
  • Initialize an empty list result that will store the values corresponding to the given key.
  • Iterate over each dictionary in the list using a for loop.
  • Check if the given key is present in the dictionary using the in operator.
  • If the key is present, append the corresponding value to the result list.
  • Return the result list after all the dictionaries in the list have been checked.

Python3

def get_values(lst, key):
    result = []
    for dictionary in lst:
        if key in dictionary:
            result.append(dictionary[key])
    return result
 
 
# Initialize list
test_list = [{'gfg': 1, 'is': 2, 'good': 3},
             {'gfg': 2}, {'best': 3, 'gfg': 4}]
 
# Get values of 'gfg' key
res = get_values(test_list, 'gfg')
 
# Print the result
print("The values corresponding to key : " + str(res))

                    

Output
The values corresponding to key : [1, 2, 4]

Time complexity: O(nm), where n is the number of dictionaries in the list and m is the average number of keys in each dictionary. 
Auxiliary space: O(k), where k is the number of values corresponding to the given key in the list.

Method #7: Using  heapq:

Step-by-step approach:

  • Create a list test_list containing dictionaries with key-value pairs.
  • Use list comprehension to create a new list res.
  • For each dictionary d in test_list, check if the key ‘gfg’ is in the dictionary.
  • If the key ‘gfg’ is in the dictionary, get its value and append it to the list res.
  • Print the list res.

Python3

import heapq
 
# initializing list
test_list = [{'gfg': 1, 'is': 2, 'good': 3},
            {'gfg': 2}, {'best': 3, 'gfg': 4}]
 
# Using heapq to get values of particular key in list of dictionaries
res = [d['gfg'] for d in test_list if 'gfg' in d]
 
# printing result
print("The values corresponding to key : " + str(res))
#This code is contributed by Rayudu.

                    

Output
The values corresponding to key : [1, 2, 4]

Time Complexity:
The time complexity  is O(N), where N is the total number of key-value pairs in all the dictionaries in the list. This is because we need to iterate over each dictionary once and perform constant time operations to check for the presence of the key ‘gfg’ and retrieve its value.

Auxiliary Space:
The space complexity  is O(M), where M is the total number of dictionaries in the list that contain the key ‘gfg’. This is because we create a new list res that has the same length as the number of dictionaries that contain the key ‘gfg’, and each element of the list is a single integer value that takes up a constant amount of space.

Method #8: Using filter() and lambda function

Use the filter() method along with a lambda function to filter out the dictionaries that contain the given key and then use a list comprehension to extract the corresponding values.

Step-by-step approach:

  • Define a lambda function that takes a dictionary and a key as arguments and returns True if the key is present in the dictionary, else False.
  • Use filter() method to filter out the dictionaries that contain the given key.
  • Use a list comprehension to extract the corresponding values from the filtered dictionaries.
  • Return the list of values.

Python3

def get_values(lst, key):
    filter_func = lambda d: key in d
    filtered_list = filter(filter_func, lst)
    result = [d[key] for d in filtered_list]
    return result
 
# Initialize list
test_list = [{'gfg': 1, 'is': 2, 'good': 3},
             {'gfg': 2}, {'best': 3, 'gfg': 4}]
 
# Get values of 'gfg' key
res = get_values(test_list, 'gfg')
 
# Print the result
print("The values corresponding to key : " + str(res))

                    

Output
The values corresponding to key : [1, 2, 4]

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



Last Updated : 16 May, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads
Complete Tutorials