Open In App

Python – Remove Key from Dictionary List

Last Updated : 16 Mar, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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))


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}]

Time complexity: O(n), where n is the number of dictionaries in the list.
Auxiliary Space: O(1), as the algorithm uses a constant amount of extra space, independent of the size of the input.

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))


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}]

Time complexity; O(nm),
Auxiliary space: O(nm), 

Method#3: Using Recursive method.

Python3




# Python3 code to demonstrate working of
# Remove Key from Dictionary List
# Using recursive function
 
def remove_key(data, del_key):
    # checking if data is a dictionary or list
    if isinstance(data, dict):
        # if key is present in dictionary then remove it
        data.pop(del_key, None)
        #iterating over all the keys in the dictionary
        for key in data:
            # calling function recursively for nested dictionaries
            remove_key(data[key], del_key)
    elif isinstance(data, list):
        #iterating over all the items of the list
        for item in data:
            # calling function recursively for all elements of the list
            remove_key(item, del_key)
             
# initializing list
test_list = [{'Gfg': 1, 'id': 2, 'best': 8},
             {'Gfg': 4, 'id': 4, 'best': 10},
             {'Gfg': 4, 'id': 8, 'best': 11}]
# initializing key
del_key = 'id'
# printing original list
print("The original list is : " + str(test_list))
# printing result
remove_key(test_list, del_key)
 
# printing result
print("The original list is : " + str(test_list))
#this code contributed by tvsk


Output

The original list is : [{'Gfg': 1, 'id': 2, 'best': 8}, {'Gfg': 4, 'id': 4, 'best': 10}, {'Gfg': 4, 'id': 8, 'best': 11}]
The original list is : [{'Gfg': 1, 'best': 8}, {'Gfg': 4, 'best': 10}, {'Gfg': 4, 'best': 11}]

Time Complexity: O(n)
Auxiliary Space:O(n)

Method #4: Using list comprehension + lambda function

In this method, use the map() function with a lambda function that filters out the del_key from each dictionary in the test_list. The lambda function is applied to each dictionary using map(), and the resulting list of dictionaries is converted to a list using list().

Python3




test_list = [{'Gfg': 1, 'id': 2, 'best': 8},
             {'Gfg': 4, 'id': 4, 'best': 10},
             {'Gfg': 4, 'id': 8, 'best': 11}]
 
del_key = 'id'
 
result = list(map(lambda d: {k: v for k, v in d.items() if k != del_key}, test_list))
 
print("The modified list: " + str(result))


Output

The modified list: [{'Gfg': 1, 'best': 8}, {'Gfg': 4, 'best': 10}, {'Gfg': 4, 'best': 11}]

Time complexity: O(nm), where n is the number of dictionaries in the test_list, and m is the number of key-value pairs in each dictionary.
Auxiliary space: O(nm), since we are creating a new dictionary for each dictionary in the test_list with all keys except the specified del_key.

Method #5: Using copy() and del keyword

This method creates a new list without the specified key-value pair by iterating through the original list, making a copy of each dictionary using the copy() method, deleting the key-value pair using the del keyword, and appending the modified dictionary to the new list.

Python3




test_list = [{'Gfg': 1, 'id': 2, 'best': 8},             {'Gfg': 4, 'id': 4, 'best': 10},             {'Gfg': 4, 'id': 8, 'best': 11}]
 
del_key = 'id'
 
result_list = []
 
for d in test_list:
    new_dict = d.copy()
    del new_dict[del_key]
    result_list.append(new_dict)
 
print("The original list is: " + str(test_list))
print("The modified list is: " + str(result_list))


Output

The original list is: [{'Gfg': 1, 'id': 2, 'best': 8}, {'Gfg': 4, 'id': 4, 'best': 10}, {'Gfg': 4, 'id': 8, 'best': 11}]
The modified list is: [{'Gfg': 1, 'best': 8}, {'Gfg': 4, 'best': 10}, {'Gfg': 4, 'best': 11}]

Time complexity: O(n), where n is the number of dictionaries in the test_list.
Auxiliary space: O(n), as well. This is because a new list (result_list) is created that holds the modified dictionaries. 

Method #6: Using filter() and lambda function

In this method, use the filter() function with a lambda function to remove the specified key from each dictionary in the list.

Step-by-step approach:

  1. Define a lambda function that takes a dictionary as an argument and returns a new dictionary that is the same as the original dictionary, but with the specified key removed.
  2. Use the filter() function to create a new iterator that returns only the dictionaries that pass the filter condition. The filter condition is the lambda function defined in step 1.
  3. Convert the iterator to a list and assign it to the original list variable.
  4. Print the modified list.

Python3




# Python3 code to demonstrate working of
# Remove Key from Dictionary List
# Using filter() and lambda function
 
# 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 filter() and lambda function
test_list = list(filter(lambda x: x.pop(del_key, None) or True, test_list))
 
# printing result
print("The modified list : " + str(test_list))


Output

The original list is : [{'Gfg': 1, 'id': 2, 'best': 8}, {'Gfg': 4, 'id': 4, 'best': 10}, {'Gfg': 4, 'id': 8, 'best': 11}]
The modified list : [{'Gfg': 1, 'best': 8}, {'Gfg': 4, 'best': 10}, {'Gfg': 4, 'best': 11}]

Time complexity: O(n), where n is the number of dictionaries in the list.
Auxiliary space: O(1), because we are modifying the original list in place and not creating a new list. However, we are creating a lambda function and an iterator, which use some additional memory.



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads