Open In App

Python | Removing dictionary from list of dictionaries

Last Updated : 02 May, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

The common utility to remove the dictionary corresponding to particular key in a list of dictionaries is also a problem whose concise version is always helpful. This has application in web development due to the introduction of No-SQL databases, which work mostly on Key-Value pairs. Let’s discuss certain ways in which this task can be performed. 

Method #1 : Using del + loop In the naive method of performing this particular task, we require to use del to delete the particular key if it matches the key that is required to be deleted. 

Python3




# Python3 code to demonstrate
# to delete dictionary in list
# using del + loop
 
# initializing list of dictionaries
test_list = [{"id" : 1, "data" : "HappY"},
             {"id" : 2, "data" : "BirthDaY"},
             {"id" : 3, "data" : "Rash"}]
 
# printing original list
print ("The original list is : " + str(test_list))
 
# using del + loop
# to delete dictionary in list
for i in range(len(test_list)):
    if test_list[i]['id'] == 2:
        del test_list[i]
        break
 
# printing result
print ("List after deletion of dictionary : " +  str(test_list))


Output:

The original list is : [{‘id’: 1, ‘data’: ‘HappY’}, {‘id’: 2, ‘data’: ‘BirthDaY’}, {‘id’: 3, ‘data’: ‘Rash’}] List after deletion of dictionary : [{‘id’: 1, ‘data’: ‘HappY’}, {‘id’: 3, ‘data’: ‘Rash’}]

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

Method #2 : Using list comprehension This method works by constructing the whole new or overwriting the original list by all the dictionaries except the one that has the key that has to be deleted. 

Python3




# Python3 code to demonstrate
# to delete dictionary in list
# using list comprehension
 
# initializing list of dictionaries
test_list = [{"id" : 1, "data" : "HappY"},
             {"id" : 2, "data" : "BirthDaY"},
             {"id" : 3, "data" : "Rash"}]
 
# printing original list
print ("The original list is : " + str(test_list))
 
# using list comprehension
# to delete dictionary in list
res = [i for i in test_list if not (i['id'] == 2)]
 
# printing result
print ("List after deletion of dictionary : " +  str(res))


Output:

The original list is : [{‘id’: 1, ‘data’: ‘HappY’}, {‘id’: 2, ‘data’: ‘BirthDaY’}, {‘id’: 3, ‘data’: ‘Rash’}] List after deletion of dictionary : [{‘id’: 1, ‘data’: ‘HappY’}, {‘id’: 3, ‘data’: ‘Rash’}]

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

Method #3 : Using filter() + lambda filter function can be used to get the dictionary with the required key and lambda function is used to iterate to the lists elements one by one before which filter can perform its task. 

Python3




# Python3 code to demonstrate
# to delete dictionary in list
# using filter() + lambda
 
# initializing list of dictionaries
test_list = [{"id" : 1, "data" : "HappY"},
             {"id" : 2, "data" : "BirthDaY"},
             {"id" : 3, "data" : "Rash"}]
 
# printing original list
print ("The original list is : " + str(test_list))
 
# using filter() + lambda
# to delete dictionary in list
res = list(filter(lambda i: i['id'] != 2, test_list))
 
# printing result
print ("List after deletion of dictionary : " +  str(res))


Output:

The original list is : [{‘id’: 1, ‘data’: ‘HappY’}, {‘id’: 2, ‘data’: ‘BirthDaY’}, {‘id’: 3, ‘data’: ‘Rash’}] List after deletion of dictionary : [{‘id’: 1, ‘data’: ‘HappY’}, {‘id’: 3, ‘data’: ‘Rash’}]

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

Method 4: Using pop() method

Step-by-step approach:

  • Initialize a list of dictionaries called test_list with 3 dictionaries.
  • Print the original list using the print() function.
  • Create a variable index and set it to None.
  • Use a for loop with enumerate() function to iterate through each dictionary in the test_list. The enumerate() function returns a tuple with two values: the index of the current item and the item itself.
  • Check if the value of the ‘id’ key in the current dictionary is equal to 2. If it is, then assign the index of the current item to the index variable and break out of the loop using the break keyword.
  • Use an if statement to check if the index variable is not None.
  • If the index variable is not None, use the pop() method to remove the dictionary at the specified index from the test_list.
  • Print the updated list using the print() function.

Below is the implementation of the above approach:

Python3




# Python3 code to demonstrate
# to delete dictionary in list
# using pop() method
 
# initializing list of dictionaries
test_list = [{"id" : 1, "data" : "HappY"},
             {"id" : 2, "data" : "BirthDaY"},
             {"id" : 3, "data" : "Rash"}]
 
# printing original list
print("The original list is: " + str(test_list))
 
# finding the index of the dictionary with the required 'id'
index = None
for i, d in enumerate(test_list):
    if d['id'] == 2:
        index = i
        break
 
# using pop() method to remove the dictionary at the specified index
if index is not None:
    test_list.pop(index)
 
# printing the updated list
print("List after deletion of dictionary: " + str(test_list))


Output

The original list is: [{'id': 1, 'data': 'HappY'}, {'id': 2, 'data': 'BirthDaY'}, {'id': 3, 'data': 'Rash'}]
List after deletion of dictionary: [{'id': 1, 'data': 'HappY'}, {'id': 3, 'data': 'Rash'}]

Time complexity: O(n) since we need to iterate over the list to find the index of the dictionary to be deleted. 
Auxiliary space: O(1) since we are not creating any additional data structures.

Approach: Using remove() method

We can use the remove() method of list to remove the dictionary with the required key from the list of dictionaries. The remove() method removes the first occurrence of the specified element in the list. We can find the dictionary with the required key using a loop and then remove it using the remove() method.

Algorithm:

Initialize a list of dictionaries called test_list with 3 dictionaries.
Print the original list using the print() function.
Use a for loop to iterate through each dictionary in the test_list.
Check if the value of the ‘id’ key in the current dictionary is equal to 2.
If it is, then remove the current dictionary from the test_list using the remove() method and break out of the loop using the break keyword.
Print the updated list using the print() function.

Python3




# Python3 code to demonstrate
# to delete dictionary in list
# using remove() method
 
# initializing list of dictionaries
test_list = [{"id": 1, "data": "HappY"},
             {"id": 2, "data": "BirthDaY"},
             {"id": 3, "data": "Rash"}]
 
# printing original list
print("The original list is : " + str(test_list))
 
# using remove() method
# to delete dictionary in list
for d in test_list:
    if d["id"] == 2:
        test_list.remove(d)
        break
 
# printing result
print("List after deletion of dictionary : " + str(test_list))


Output

The original list is : [{'id': 1, 'data': 'HappY'}, {'id': 2, 'data': 'BirthDaY'}, {'id': 3, 'data': 'Rash'}]
List after deletion of dictionary : [{'id': 1, 'data': 'HappY'}, {'id': 3, 'data': 'Rash'}]

Time Complexity: O(n) for looping over dictionary.
Space Complexity: O(1) as we are not storing any list.



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

Similar Reads