Skip to content
Related Articles

Related Articles

Python – Remove records if Key not present

View Discussion
Improve Article
Save Article
Like Article
  • Last Updated : 21 Feb, 2022

Sometimes, while working with Python dictionaries, we can have a problem in which we need to remove all the dictionaries in which a particular key is not present. This kind of problem can have applications in many domains such as day-day programming and data domain. Let’s discuss certain ways in which this task can be performed.
 

Input : test_list = [{‘Gfg’ : 1, ‘Best’ : 3}, {‘Gfg’ : 3, ‘Best’ : 5}, {‘Best’ : 3}] , K = ‘Best’ 
Output : [{‘Gfg’ : 1, ‘Best’ : 3}, {‘Gfg’ : 3, ‘Best’ : 5}, {‘Best’ : 3}]
Input : test_list = [{‘Gfg’ : 1, ‘Best’ : 3}, {‘Gfg’ : 3, ‘Best’ : 5}, {‘Best’ : 3}], K = ‘good’ 
Output : [] 
 

Method #1: Using list comprehension 
This is one of the ways in which this task can be performed. In this, we iterate and test for key presence using list comprehension and conditional statements.
 

Python3




# Python3 code to demonstrate working of
# Remove records if Key not present
# Using list comprehension
 
# initializing list
test_list = [{'Gfg' : 1, 'Best' : 3},
             {'Gfg' : 3, 'Best' : 5},
             {'Best' : 3}]
 
# printing original list
print("The original list : " + str(test_list))
 
# initializing K Key
K = 'Gfg'
 
# Remove records if Key not present
# Using list comprehension
res = [ele for ele in test_list if K in ele]
         
# printing result
print("List after filtration : " + str(res))

Output : 

The original list : [{'Gfg': 1, 'Best': 3}, {'Gfg': 3, 'Best': 5}, {'Best': 3}]
List after filteration : [{'Gfg': 1, 'Best': 3}, {'Gfg': 3, 'Best': 5}]

 

 
Method #2 : Using list comprehension + keys() 
The combination of the above functions can be used to solve this problem. In this, we perform the task of extraction of all the keys using keys(), reduces the overhead of checking in items.
 

Python3




# Python3 code to demonstrate working of
# Remove records if Key not present
# Using list comprehension + keys()
 
# initializing list
test_list = [{'Gfg' : 1, 'Best' : 3},
             {'Gfg' : 3, 'Best' : 5},
             {'Best' : 3}]
 
# printing original list
print("The original list : " + str(test_list))
 
# initializing K Key
K = 'Gfg'
 
# Remove records if Key not present
# Using list comprehension + keys()
res = [ele for ele in test_list if K in ele.keys()]
         
# printing result
print("List after filtration : " + str(res))

Output : 

The original list : [{'Gfg': 1, 'Best': 3}, {'Gfg': 3, 'Best': 5}, {'Best': 3}]
List after filteration : [{'Gfg': 1, 'Best': 3}, {'Gfg': 3, 'Best': 5}]

 


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!