Python Program to extract Dictionaries with given Key from a list of dictionaries
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.
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning - Basic Level Course
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 presence of key using in operator, keys are extracted using 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 listtest_list = [{'gfg': 2, 'is': 8, 'good': 3}, {'gfg': 1, 'for': 10, 'geeks': 9}, {'love': 3}] # printing original listprint("The original list is : " + str(test_list)) # initializing keykey = 'gfg' # checking for key using in operator# keys() used to get keysres = [sub for sub in test_list if key in list(sub.keys())] # printing resultprint("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}]
Method 2 : Using filter() and lambda
In this, we perform task of filtering using filter() and lambda function is used to inject logic into filtration. The in operator is used to check presence of specific key.
Example:
Python3
# Python3 code to demonstrate working of# Extract Dictionaries with given Key# Using filter() + lambda # initializing listtest_list = [{'gfg': 2, 'is': 8, 'good': 3}, {'gfg': 1, 'for': 10, 'geeks': 9}, {'love': 3, 'gfg': 4}] # printing original listprint("The original list is : " + str(test_list)) # initializing keykey = 'good' # checking for key using in operator# keys() used to get keys# filter() + lambda used to perform filerationres = list(filter(lambda sub: key in list(sub.keys()), test_list)) # printing resultprint("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}]

