Skip to content
Related Articles
Open in App
Not now

Related Articles

Python | Get values of particular key in list of dictionaries

Improve Article
Save Article
  • Last Updated : 20 Mar, 2023
Improve Article
Save Article

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. 

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]

The time complexity of the code is 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. 

The space complexity of the code is 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.

Algorithm:

  1. Define a function that takes a list of dictionaries (lst) and a key to search for (key) as input.
  2. Base case: If the list is empty, return an empty list.
  3. Get the first dictionary in the list.
  4. Check if the key is in the first dictionary.
  5. If the key is in the dictionary, add the value to the result list.
  6. If the key is not in the dictionary, the result list is empty.
  7. Recursively call the function on the rest of the list.
  8. Append the result of the recursive call to the current result list.
  9. 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.


My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!