Skip to content
Related Articles

Related Articles

Improve Article
Python – Remove records if Key not present
  • Last Updated : 03 Jul, 2020

Sometimes, while working with Python dictionaries, we can have a problem in which we need to remove all the dictionaries in which particular key is not present. This kind of problem can have application 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 statement.




# 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 filteration : " + 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 above functions can be used to solve this problem. In this, we perform the task of extraction of all the keys using keys(), reduces overhead of checking in items.




# 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 filteration : " + 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}]

 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




My Personal Notes arrow_drop_up
Recommended Articles
Page :