Python – Remove Key from Dictionary List
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.
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
Python3
# Python3 code to demonstrate working of# Remove Key from Dictionary List# Using loop + del# initializing listtest_list = [{'Gfg' : 1, 'id' : 2, 'best' : 8 }, {'Gfg' : 4, 'id' : 4, 'best': 10}, {'Gfg' : 4, 'id' : 8, 'best': 11}]# printing original listprint("The original list is : " + str(test_list))# initializing keydel_key = 'id'# Remove Key from Dictionary List# Using loop + delfor items in test_list: if del_key in items: del items[del_key]# printing resultprint("The modified list : " + str(test_list)) |
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 comprehension + 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
# Python3 code to demonstrate working of# Remove Key from Dictionary List# Using list comprehension + dictionary comprehension# initializing listtest_list = [{'Gfg' : 1, 'id' : 2, 'best' : 8 }, {'Gfg' : 4, 'id' : 4, 'best': 10}, {'Gfg' : 4, 'id' : 8, 'best': 11}]# printing original listprint("The original list is : " + str(test_list))# initializing keydel_key = 'id'# Remove Key from Dictionary List# Using list comprehension + dictionary comprehensionres = [{key : val for key, val in sub.items() if key != del_key} for sub in test_list]# printing resultprint("The modified list : " + str(res)) |
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}]


