Python Program to extract Dictionaries with given Key from a list of dictionaries
Last Updated :
21 Apr, 2023
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))
OutputThe 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))
OutputThe 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.
OutputThe 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))
OutputThe 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))
OutputThe 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 program to divide dictionary and its keys into K equal dictionaries
Given a dictionary, divide it into an equal dictionary list of size k, by dividing each key's value. Input : test_dict = {"Gfg" : 9, "is" : 6, "best" : 12} , K = 3 Output : [{'Gfg': 3.0, 'is': 2.0, 'best': 4.0}, {'Gfg': 3.0, 'is': 2.0, 'best': 4.0}, {'Gfg': 3.0, 'is': 2.0, 'best': 4.0}] Explanation
3 min read
Convert Dictionary of Dictionaries to Python List of Dictionaries
We are given dictionary of dictionaries we need to convert it to list of dictionaries. For example, For example, we are having d = { 'A': {'color': 'red', 'shape': 'circle'}, 'B': {'color': 'blue', 'shape': 'square'}, 'C': {'color': 'green', 'shape': 'triangle'} } we need to convert it to a list of
2 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. lengt
7 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.
5 min read
Removing Dictionary from List of Dictionaries - Python
We are given a list of dictionaries, and our task is to remove specific dictionaries based on a condition. For instance given the list: a = [{'x': 10, 'y': 20}, {'x': 30, 'y': 40}, {'x': 50, 'y': 60}], we might want to remove the dictionary where 'x' equals 30 then the output will be [{'x': 10, 'y':
3 min read
Python Program to display keys with same values in a dictionary List
Given a list with all dictionary elements, the task is to write a Python program to extract keys having similar values across all dictionaries. Examples: Input : test_list = [{"Gfg": 5, "is" : 8, "best" : 0}, {"Gfg": 5, "is" : 1, "best" : 0}, {"Gfg": 5, "is" : 0, "best" : 0}] Output : ['Gfg', 'best'
5 min read
Python program to extract key-value pairs with substring in a dictionary
Given a dictionary list, extract all the dictionaries which have substring present in particular key. Input : [{"Gfg" : "4", "best" : "1"}, {"Gfg" : "good CS content", "best" : "10"}], K = "Gfg", sub_str = "CS" Output : [{'Gfg': 'good CS content', 'best': '10'}] Explanation : "Gfg" has "CS" as subst
7 min read
Python - Convert Dictionaries List to Order Key Nested dictionaries
Given list of dictionaries, our task is to convert a list of dictionaries into a dictionary where each key corresponds to the index of the dictionary in the list and the value is the dictionary itself. For example: consider this list of dictionaries: li = [{"Gfg": 3, 4: 9}, {"is": 8, "Good": 2}] the
3 min read
Python | Split dictionary of lists to list of dictionaries
Conversion from one data type to other is essential in various facets of programming. Be it development or competitive programming. Hence knowledge of it is quite useful and necessary. Let's discuss certain methods by which dictionary of list can be converted to the corresponding list of dictionarie
4 min read
Get all Unique Keys from a List of Dictionaries - Python
Our task is to get all unique keys from a list of dictionaries and we are given a list where each element is a dictionary, we need to extract and return a list of keys that appear across all dictionaries. The result should contain each key only once regardless of how many times it appears. For examp
3 min read