The Wayback Machine - https://web.archive.org/web/20240916062420/https://www.geeksforgeeks.org/python-removing-dictionary-from-list-of-dictionaries/
Open In App

Python | Removing dictionary from list of dictionaries

Last Updated : 02 May, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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.



Previous Article
Next Article

Similar Reads

Convert Dictionary of Dictionaries to Python List of Dictionaries
Dictionaries are powerful data structures in Python, allowing the storage of key-value pairs. Sometimes, we encounter scenarios where we have a dictionary of dictionaries, and we need to convert it into a list of dictionaries for easier manipulation or processing. In this article, we'll explore five different methods to achieve this conversion, eac
3 min read
Python - Convert Dictionaries List to Order Key Nested dictionaries
Given list of dictionaries, convert to ordered key dictionary with each key contained dictionary as its nested value. Input : test_list = [{"Gfg" : 3, 4 : 9}, {"is": 8, "Good" : 2}] Output : {0: {'Gfg': 3, 4: 9}, 1: {'is': 8, 'Good': 2}} Explanation : List converted to dictionary with index keys. Input : test_list = [{"is": 8, "Good" : 2}] Output :
6 min read
Python Program to extract Dictionaries with given Key from a list of dictionaries
Given a list of dictionaries, the task is to write a python program that extracts only those dictionaries that contain a specific given key value. Input : test_list = [{'gfg' : 2, 'is' : 8, 'good' : 3}, {'gfg' : 1, 'for' : 10, 'geeks' : 9}, {'love' : 3}], key= "gfg"Output : [{'gfg': 2, 'is': 8, 'good': 3}, {'gfg' : 1, 'for' : 10, 'geeks' : 9}] Expl
6 min read
Convert a List of Dictionaries into a Set of Dictionaries
Python's versatility allows developers to manipulate data in various ways. When working with a list of dictionaries, there might be scenarios where you want to convert it into a set of dictionaries to eliminate duplicates or for other reasons. In this article, we'll explore three different methods to achieve this goal with code examples. Convert A
3 min read
Python - Combine two dictionaries having key of the first dictionary and value of the second dictionary
Given two dictionaries. The task is to merge them in such a way that the resulting dictionary contains the key from the first dictionary and the value from the second dictionary. Examples: Input : test_dict1 = {"Gfg" : 20, "is" : 36, "best" : 100}, test_dict2 = {"Gfg2" : 26, "is2" : 20, "best2" : 70} Output : {'Gfg': 26, 'is': 20, 'best': 70} Expla
8 min read
Python - Convert list of dictionaries to Dictionary Value list
Given a list of dictionary, convert to dictionary with same key mapped with all values in as value list. Input : test_list = [{"Gfg" : 6, "is" : 9, "best" : 10}, {"Gfg" : 8, "is" : 11, "best" : 19}] Output : {'Gfg': [6, 8], 'is': [9, 11], 'best': [10, 19]} Explanation : 6, 8 of "Gfg" mapped as value list, similarly every other. Input : test_list =
10 min read
Python | Split dictionary of lists to list of dictionaries
Conversion from one data type to other is essential in various facets of programming. Be it development or competitive programming. Hence knowledge of it is quite useful and necessary. Let's discuss certain methods by which dictionary of list can be converted to the corresponding list of dictionaries. Method #1 : Using list comprehension We can use
4 min read
Python - Remove dictionary from a list of dictionaries if a particular value is not present
Given a list of dictionaries, remove all dictionaries which don't have K as a value. Examples: Input : test_list = [{"Gfg" : 4, "is" : 8, "best" : 9}, {"Gfg" : 3, "is": 7, "best" : 5}], K = 7 Output : [{'Gfg': 4, 'is': 8, 'best': 9}] Explanation : Resultant dictionary doesn't contain 7 as any element.Input : test_list = [{"Gfg" : 4, "is" : 7, "best
5 min read
Python Program to Convert dictionary string values to List of dictionaries
Given a dictionary with values as delimiter separated values, the task is to write a python program to convert each string as different value in list of dictionaries. Input : test_dict = {"Gfg" : "1:2:3", "best" : "4:8:11"} Output : [{'Gfg': '1', 'best': '4'}, {'Gfg': '2', 'best': '8'}, {'Gfg': '3', 'best': '11'}] Explanation : List after dictionar
2 min read
Python - Convert list of dictionaries to dictionary of lists
In this article, we will discuss how to convert a list of dictionaries to a dictionary of lists. Method 1: Using for loop By iterating based on the first key we can convert list of dict to dict of list. Python program to create student list of dictionaries C/C++ Code # create a list of dictionaries # with student data data = [ {'name': 'sravan', 's
3 min read
Python - Removing Nested None Dictionaries
Sometimes, while working with Records, we can have a problem in which we need to perform the removal of nested records from the dictionary which are empty. This can have application in data preprocessing. Lets discuss certain ways in which this task can be performed. Method #1 : Using dict() + filter() This is one of the way in which this task can
4 min read
Python | Remove duplicate dictionaries from nested dictionary
Given a nested dictionary, the task is to remove duplicate dictionaries from the dictionary. Given below are few methods to complete the given task. Method #1: Using Naive Method C/C++ Code # Python code to demonstrate # for removing duplicate values from dictionary # initialising dictionary ini_dict = {'a':{'b':1, 'c':2}, 'b':{'b':1, 'c':2}, 'c':{
6 min read
Python - Convert dictionary to K sized dictionaries
Given a Dictionary, divide dictionary into K sized different dictionaries list. Input : test_dict = {'Gfg' : 1, 'is' : 2, 'best' : 3, 'for' : 4, 'geeks' : 5, 'CS' : 6}, K = 3 Output : [{'Gfg': 1, 'is': 2, 'best': 3}, {'for': 4, 'geeks': 5, 'CS': 6}] Explanation : Divided into size of 3 keys. Input : test_dict = {'Gfg' : 1, 'is' : 2, 'best' : 3, 'fo
4 min read
Python program to divide dictionary and its keys into K equal dictionaries
Given a dictionary, divide it into an equal dictionary list of size k, by dividing each key's value. Input : test_dict = {"Gfg" : 9, "is" : 6, "best" : 12} , K = 3 Output : [{'Gfg': 3.0, 'is': 2.0, 'best': 4.0}, {'Gfg': 3.0, 'is': 2.0, 'best': 4.0}, {'Gfg': 3.0, 'is': 2.0, 'best': 4.0}] Explanation : Values distributed equally among dictionaries. I
3 min read
Python - Convert Flat dictionaries to Nested dictionary
Sometimes, while working with records, we can have a problem in which we need to perform the task of conversion of multiple flat dictionaries to a single nested dictionary. This can have applications in many domains in which data is used extensively. Let's discuss certain ways by which we can convert flat dictionaries into nested dictionaries. Conv
4 min read
Convert Dictionary Value list to Dictionary List Python
Sometimes, while working with Python Dictionaries, we can have a problem in which we need to convert dictionary list to nested records dictionary taking each index of dictionary list value and flattening it. This kind of problem can have application in many domains. Let's discuss certain ways in which this task can be performed. Input : test_list =
9 min read
Create Pandas Dataframe from Dictionary of Dictionaries
In this article, we will discuss how to create a pandas dataframe from the dictionary of dictionaries in Python. Method 1: Using DataFrame() We can create a dataframe using Pandas.DataFrame() method. Syntax: pandas.DataFrame(dictionary) where pandas are the module that supports DataFrame data structureDataFrame is the datastructure that converts di
2 min read
Python - Convert List of Dictionaries to List of Lists
Sometimes, while working with Python data, we can have a problem in which we need to convert the list of dictionaries into a list of lists, this can be simplified by appending the keys just once if they are repetitive as mostly in records, this saves memory space. This type of problem can have applications in the web development domain. Let's discu
7 min read
Python - Sort dictionaries list by Key's Value list index
Given list of dictionaries, sort dictionaries on basis of Key's index value. Input : [{"Gfg" : [6, 7, 8], "is" : 9, "best" : 10}, {"Gfg" : [2, 0, 3], "is" : 11, "best" : 19}, {"Gfg" : [4, 6, 9], "is" : 16, "best" : 1}], K = "Gfg", idx = 0 Output : [{'Gfg': [2, 0, 3], 'is': 11, 'best': 19}, {'Gfg': [4, 6, 9], 'is': 16, 'best': 1}, {'Gfg': [6, 7, 8],
14 min read
Python - Convert List to List of dictionaries
Given list values and keys list, convert these values to key value pairs in form of list of dictionaries. Input : test_list = ["Gfg", 3, "is", 8], key_list = ["name", "id"] Output : [{'name': 'Gfg', 'id': 3}, {'name': 'is', 'id': 8}] Explanation : Values mapped by custom key, "name" -> "Gfg", "id" -> 3. Input : test_list = ["Gfg", 10], key_li
4 min read
Filter List of Python Dictionaries by Key in Python
Filtering a list of dictionaries in Python based on a specific key is a common task in data manipulation and analysis. Whether you're working with datasets or dictionaries, the ability to extract relevant information efficiently is crucial. In this article, we will explore some simple and commonly used methods to filter a list of dictionaries in Py
3 min read
Python program to update a dictionary with the values from a dictionary list
Given a dictionary and dictionary list, update the dictionary with dictionary list values. Input : test_dict = {"Gfg" : 2, "is" : 1, "Best" : 3}, dict_list = [{'for' : 3, 'all' : 7}, {'and' : 1, 'CS' : 9}] Output : {'Gfg': 2, 'is': 1, 'Best': 3, 'for': 3, 'all': 7, 'and': 1, 'CS': 9} Explanation : All dictionary keys updated in single dictionary. I
8 min read
Python Program to create a sub-dictionary containing all keys from dictionary list
Given the dictionary list, our task is to create a new dictionary list that contains all the keys, if not, then assign None to the key and persist of each dictionary. Example: Input : test_list = [{'gfg' : 3, 'is' : 7}, {'gfg' : 3, 'is' : 1, 'best' : 5}, {'gfg' : 8}]Output : [{'is': 7, 'best': None, 'gfg': 3}, {'is': 1, 'best': 5, 'gfg': 3}, {'is':
8 min read
Ways to sort list of dictionaries by values in Python - Using lambda function
In this article, we will cover how to sort a dictionary by value in Python. Sorting has always been a useful utility in day-to-day programming. Dictionary in Python is widely used in many applications ranging from competitive domain to developer domain(e.g. handling JSON data). Having the knowledge to sort dictionaries according to their values can
2 min read
Python | Set Difference in list of dictionaries
The difference of two lists have been discussed many times, but sometimes we have a large number of data and we need to find the difference i.e the elements in dict2 not in 1 to reduce the redundancies. Let's discuss certain ways in which this can be done. Method #1 : Using list comprehension The naive method to iterate both the list and extract th
3 min read
Python | Sum list of dictionaries with same key
You have given a list of dictionaries, the task is to return a single dictionary with sum values with the same key. Let's discuss different methods to do the task. Method #1: Using reduce() + operator Step-by-step approach: Import necessary modules - collections, functools, and operator.Initialize a list of dictionaries called "ini_dict" that conta
7 min read
Python | Sort given list of dictionaries by date
Given a list of dictionary, the task is to sort the dictionary by date. Let's see a few methods to solve the task. Method #1: Using naive approach C/C++ Code # Python code to demonstrate # sort a list of dictionary # where value date is in string # Initialising list of dictionary ini_list = [{'name':'akash', 'd.o.b':'1997-03-02'}, {'name':'manjeet'
2 min read
Python | Flatten given list of dictionaries
Given a list of the dictionaries, the task is to convert it into single dictionary i.e flattening a list of dictionaries. Given below are a few methods to solve the given task. Method #1: Using Naive Method C/C++ Code # Python code to demonstrate # to flatten list of dictionaries # Initialising dictionary ini_dict = [{'a':1}, {'b':2}, {'c':3}] # pr
4 min read
Python | Merging two list of dictionaries
Given two list of dictionaries, the task is to merge these two lists of dictionaries based on some value. Merging two list of dictionariesUsing defaultdict and extend to merge two list of dictionaries based on school_id. C/C++ Code # Python code to merge two list of dictionaries # based on some value. from collections import defaultdict # List init
6 min read
Python | Get values of particular key in list of dictionaries
Sometimes, we may require a way in which we have to get all the values of the specific key from a list of dictionaries. This kind of problem has a lot of applications in the web development domain in which we sometimes have a JSON and require just to get a single column from records. Let's discuss certain ways in which this problem can be solved. M
10 min read