Skip to content
Related Articles

Related Articles

Python – Remove Key from Dictionary List
  • Last Updated : 08 May, 2020

Sometimes, while working with Python dictionaries, we can have a problem in which we need to remove a specific key from a dictionary list. This kind of problem is very common and has application in almost all domains includeing day-day programming and web development domain. Lets discuss certain ways in which this task can be performed.

Method #1 : Using loop + del
The combination of above functions can be used to solve this problem. In this, we iterate for all the keys and delete the required key from each dictionary using del.




# Python3 code to demonstrate working of 
# Remove Key from Dictionary List
# Using loop + del
  
# initializing list
test_list = [{'Gfg' 1, 'id' : 2, 'best' : 8 }, 
             {'Gfg' 4, 'id' : 4, 'best'10}, 
             {'Gfg' 4, 'id' : 8, 'best'11}]
  
# printing original list
print("The original list is : " + str(test_list))
  
# initializing key 
del_key = 'id'
  
# Remove Key from Dictionary List
# Using loop + del
for items in test_list:
    if del_key in items:
        del items[del_key]
  
# printing result 
print("The modified list : " + str(test_list)) 
Output :
The original list is : [{'best': 8, 'id': 2, 'Gfg': 1}, {'best': 10, 'id': 4, 'Gfg': 4}, {'best': 11, 'id': 8, 'Gfg': 4}]
The modified list : [{'best': 8, 'Gfg': 1}, {'best': 10, 'Gfg': 4}, {'best': 11, 'Gfg': 4}]

 

Method #2 : Using list comprehnsion + dictionary comprehension
This is yet another way in which this task can be performed. In this, we reconstruct each dictionary removing out the specific key from it.






# Python3 code to demonstrate working of 
# Remove Key from Dictionary List
# Using list comprehnsion + dictionary comprehension
  
# initializing list
test_list = [{'Gfg' 1, 'id' : 2, 'best' : 8 }, 
             {'Gfg' 4, 'id' : 4, 'best'10}, 
             {'Gfg' 4, 'id' : 8, 'best'11}]
  
# printing original list
print("The original list is : " + str(test_list))
  
# initializing key 
del_key = 'id'
  
# Remove Key from Dictionary List
# Using list comprehnsion + dictionary comprehension
res = [{key : val for key, val in sub.items() if key != del_key} for sub in test_list]
  
# printing result 
print("The modified list : " + str(res)) 
Output :
The original list is : [{'best': 8, 'id': 2, 'Gfg': 1}, {'best': 10, 'id': 4, 'Gfg': 4}, {'best': 11, 'id': 8, 'Gfg': 4}]
The modified list : [{'best': 8, 'Gfg': 1}, {'best': 10, 'Gfg': 4}, {'best': 11, 'Gfg': 4}]

 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 :