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 including day-day programming and web development domain. Let’s 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
# 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)) |
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 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 comprehension + 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)) |
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}]