Open In App

Python Program to extract Dictionaries with given Key from a list of dictionaries

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

Given a list of dictionaries, the task is to write a python program that extracts only those dictionaries that contain a specific given key value.

Input : test_list = [{‘gfg’ : 2, ‘is’ : 8, ‘good’ : 3}, {‘gfg’ : 1, ‘for’ : 10, ‘geeks’ : 9}, {‘love’ : 3}], key= “gfg”
Output : [{‘gfg’: 2, ‘is’: 8, ‘good’: 3}, {‘gfg’ : 1, ‘for’ : 10, ‘geeks’ : 9}] 
Explanation : gfg is present in first two dictionaries, hence extracted.

Input : test_list = [{‘gfg’ : 2, ‘is’ : 8, ‘good’ : 3}, {‘gfg’ : 1, ‘for’ : 10, ‘geeks’ : 9}, {‘love’ : 3, ‘gfgs’ : 4}], key = “good”
Output : [{‘gfg’: 2, ‘is’: 8, ‘good’: 3}] 
Explanation : good is present in 1st dictionary, hence extracted. 

Method 1: Using list comprehension and keys()

In this, we test for the presence of a key using in operator, keys are extracted using the key(). List comprehension is used to iterate over different dictionaries.

Example:

Python3




# Python3 code to demonstrate working of
# Extract Dictionaries with given Key
# Using list comprehension + keys()
 
# initializing list
test_list = [{'gfg': 2, 'is': 8, 'good': 3},
             {'gfg': 1, 'for': 10, 'geeks': 9},
             {'love': 3}]
 
# printing original list
print("The original list is : " + str(test_list))
 
# initializing key
key = 'gfg'
 
# checking for key using in operator
# keys() used to get keys
res = [sub for sub in test_list if key in list(sub.keys())]
 
# printing result
print("The filtered Dictionaries : " + str(res))


Output

The original list is : [{'gfg': 2, 'is': 8, 'good': 3}, {'gfg': 1, 'for': 10, 'geeks': 9}, {'love': 3}]
The filtered Dictionaries : [{'gfg': 2, 'is': 8, 'good': 3}, {'gfg': 1, 'for': 10, 'geeks': 9}]

Time Complexity: O(n), where n is the length of the given list
Auxiliary Space: O(n)

Method 2 : Using filter() and lambda

In this, we perform the task of filtering using filter() and the lambda function is used to inject logic into filtration. The in operator is used to check the presence of a specific key.

Example:

Python3




# Python3 code to demonstrate working of
# Extract Dictionaries with given Key
# Using filter() + lambda
 
# initializing list
test_list = [{'gfg': 2, 'is': 8, 'good': 3},
             {'gfg': 1, 'for': 10, 'geeks': 9},
             {'love': 3, 'gfg': 4}]
 
# printing original list
print("The original list is : " + str(test_list))
 
# initializing key
key = 'good'
 
# checking for key using in operator
# keys() used to get keys
# filter() + lambda used to perform filtration
res = list(filter(lambda sub: key in list(sub.keys()), test_list))
 
# printing result
print("The filtered Dictionaries : " + str(res))


Output

The original list is : [{'gfg': 2, 'is': 8, 'good': 3}, {'gfg': 1, 'for': 10, 'geeks': 9}, {'love': 3, 'gfg': 4}]
The filtered Dictionaries : [{'gfg': 2, 'is': 8, 'good': 3}]

Time Complexity: O(n), where n is the length of the given list
Auxiliary Space: O(n)

Method 3 : Using for loop

Python3




# Initializing list of dictionaries
test_list = [{'gfg': 2, 'is': 8, 'good': 3},
             {'gfg': 1, 'for': 10, 'geeks': 9},
             {'love': 3}]
 
# Printing original list
print("The original list is: ", test_list)
 
# Initializing key
key = 'gfg'
 
# Using for loop to extract dictionaries with given key
result = []
for sub_dict in test_list:
    if key in sub_dict:
        result.append(sub_dict)
 
# Printing result
print("The filtered dictionaries: ", result)
#This code is contributed by Vinay Pinjala.


Output

The original list is:  [{'gfg': 2, 'is': 8, 'good': 3}, {'gfg': 1, 'for': 10, 'geeks': 9}, {'love': 3}]
The filtered dictionaries:  [{'gfg': 2, 'is': 8, 'good': 3}, {'gfg': 1, 'for': 10, 'geeks': 9}]

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

Method 4: Using list comprehension and items()

Use items() method of dictionaries along with list comprehension to extract the dictionaries with the given key. In this method, iterate through the list of dictionaries using list comprehension, and check if the key exists in the dictionary using in operator with items() method.

Python3




# Python3 code to demonstrate working of
# Extract Dictionaries with given Key
# Using list comprehension + items()
 
# initializing list
test_list = [{'gfg': 2, 'is': 8, 'good': 3},
             {'gfg': 1, 'for': 10, 'geeks': 9},
             {'love': 3}]
 
# printing original list
print("The original list is : " + str(test_list))
 
# initializing key
key = 'gfg'
 
# extracting dictionaries with given key
res = [dct for dct in test_list if key in [k for k, v in dct.items()]]
 
# printing result
print("The filtered Dictionaries : " + str(res))


Output

The original list is : [{'gfg': 2, 'is': 8, 'good': 3}, {'gfg': 1, 'for': 10, 'geeks': 9}, {'love': 3}]
The filtered Dictionaries : [{'gfg': 2, 'is': 8, 'good': 3}, {'gfg': 1, 'for': 10, 'geeks': 9}]

Time complexity: O(NM), where N is the length of the list and M is the maximum number of key-value pairs in any dictionary of the list.
Auxiliary space: O(N), where N is the length of the list. This is because we are creating a new list to store the filtered dictionaries.

Method 5: Using dictionary comprehension and items()

Step-by-step approach:

  • Initialize the list of dictionaries test_list.
  • Print the original list using the print statement.
    Initialize the key key.
  • Use dictionary comprehension with items() method to create a list of dictionaries that contain the given key.
  • Print the resulting filtered list of dictionaries.

Python3




# Python3 code to demonstrate working of
# Extract Dictionaries with given Key
# Using dictionary comprehension + items()
 
# initializing list
test_list = [{'gfg': 2, 'is': 8, 'good': 3},
             {'gfg': 1, 'for': 10, 'geeks': 9},
             {'love': 3}]
 
# printing original list
print("The original list is : " + str(test_list))
 
# initializing key
key = 'gfg'
 
# using dictionary comprehension and items()
res = [d for d in test_list if key in d.keys()]
 
# printing result
print("The filtered Dictionaries : " + str(res))


Output

The original list is : [{'gfg': 2, 'is': 8, 'good': 3}, {'gfg': 1, 'for': 10, 'geeks': 9}, {'love': 3}]
The filtered Dictionaries : [{'gfg': 2, 'is': 8, 'good': 3}, {'gfg': 1, 'for': 10, 'geeks': 9}]

Time complexity: O(n), where n is the length of the input list of dictionaries, as we need to iterate over the entire list once to filter the dictionaries.
Auxiliary space: O(m), where m is the number of dictionaries that contain the given key, as we are creating a new list of those dictionaries.



Similar Reads

Python - Convert Dictionaries List to Order Key Nested dictionaries
Given list of dictionaries, convert to ordered key dictionary with each key contained dictionary as its nested value. Input : test_list = [{"Gfg" : 3, 4 : 9}, {"is": 8, "Good" : 2}] Output : {0: {'Gfg': 3, 4: 9}, 1: {'is': 8, 'Good': 2}} Explanation : List converted to dictionary with index keys. Input : test_list = [{"is": 8, "Good" : 2}] Output :
6 min read
Python - Extract Key's value from Mixed Dictionaries List
Given a list of dictionaries, with each dictionary having different keys, extract value of key K. Input : test_list = [{"Gfg" : 3, "b" : 7}, {"is" : 5, 'a' : 10}, {"Best" : 9, 'c' : 11}], K = 'b' Output : 7 Explanation : Value of b is 7. Input : test_list = [{"Gfg" : 3, "b" : 7}, {"is" : 5, 'a' : 10}, {"Best" : 9, 'c' : 11}], K = 'c' Output : 11 Ex
7 min read
Python - Extract dictionaries with Empty String value in K key
Given a List of dictionaries, extract all the dictionaries which have empty strings as values of a particular key. Input : test_list = [{"Gfg" : "4", "is" : "good", "best" : "1"}, {"Gfg" : "9", "is" : "CS", "best" : "10"}], K = "Gfg" Output : [] Explanation : No "Gfg" key is empty. Input : test_list = [{"Gfg" : "", "is" : "good", "best" : "1"}, {"G
8 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
Convert Dictionary of Dictionaries to Python List of Dictionaries
Dictionaries are powerful data structures in Python, allowing the storage of key-value pairs. Sometimes, we encounter scenarios where we have a dictionary of dictionaries, and we need to convert it into a list of dictionaries for easier manipulation or processing. In this article, we'll explore five different methods to achieve this conversion, eac
3 min read
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 - Sort dictionaries list by Key's Value list index
Given list of dictionaries, sort dictionaries on basis of Key's index value. Input : [{"Gfg" : [6, 7, 8], "is" : 9, "best" : 10}, {"Gfg" : [2, 0, 3], "is" : 11, "best" : 19}, {"Gfg" : [4, 6, 9], "is" : 16, "best" : 1}], K = "Gfg", idx = 0 Output : [{'Gfg': [2, 0, 3], 'is': 11, 'best': 19}, {'Gfg': [4, 6, 9], 'is': 16, 'best': 1}, {'Gfg': [6, 7, 8],
14 min read
Convert a List of Dictionaries into a Set of Dictionaries
Python's versatility allows developers to manipulate data in various ways. When working with a list of dictionaries, there might be scenarios where you want to convert it into a set of dictionaries to eliminate duplicates or for other reasons. In this article, we'll explore three different methods to achieve this goal with code examples. Convert A
3 min read
Python program to extract N largest dictionaries keys
Given a dictionary, extract the largest N dictionaries keys in descending order. Input : test_dict = {6 : 2, 8: 9, 3: 9, 10: 8}, N = 3 Output : [10, 8, 6] Explanation : Max. N keys extracted in descending order.Input : test_dict = {6 : 2, 8: 9, 3: 9, 10: 8}, N = 2 Output : [10, 8] Explanation : Max. N keys extracted in descending order. Method #1 :
5 min read
Python Program to extract dictionaries with maximum number of keys
Given a list of dictionaries, the task is to write a Python program to extract a dictionary with a maximum number of keys. Input : test_list = [{'Gfg' : 1}, {'Gfg' : 1, 'is' : 5, 'best' : 4}, {'Gfg' : 2, 'best' : 9}] Output : {'Gfg' : 1, 'is' : 5, 'best' : 4} Explanation : Dictionary with max. length 3 is output.Input : test_list = [{'Gfg' : 1}, {'
7 min read
three90RightbarBannerImg