Remove a Dictionary from a List of Dictionaries in Python

avatar
Borislav Hadzhiev

Last updated: Apr 9, 2024
7 min

banner

# Table of Contents

  1. Remove a dictionary from a list of dictionaries in Python
  2. Remove a dictionary from a list of dictionaries using list comprehension
  3. Remove a dictionary from a list of dictionaries using reassignment
  4. Remove empty dictionaries from a list of dictionaries

# Remove a dictionary from a list of dictionaries in Python

To remove a dictionary from a list of dictionaries:

  1. Use a for loop to iterate over a copy of the list.
  2. Check if each dictionary is the one to be removed.
  3. Use the list.remove() method to remove the matching dictionary from the list.
main.py
my_list = [ {'id': 1, 'fruit': 'apple'}, {'id': 2, 'fruit': 'banana'}, {'id': 3, 'fruit': 'kiwi'}, ] for item in my_list.copy(): if item.get('id') == 2: my_list.remove(item) break # ๐Ÿ‘‡๏ธ [{'id': 1, 'fruit': 'apple'}, {'id': 3, 'fruit': 'kiwi'}] print(my_list)

remove dictionary from list of dictionaries

The code for this article is available on GitHub

The example uses a for loop to remove a dictionary from a list of dictionaries.

We used the list.copy() method to get a copy of the list.

The list.copy() method returns a shallow copy of the object on which the method was called.

This is necessary because we aren't allowed to remove elements from a list while iterating over it.

However, we can iterate over a copy of the list and remove elements from the original list.

main.py
my_list = [ {'id': 1, 'fruit': 'apple'}, {'id': 2, 'fruit': 'banana'}, {'id': 3, 'fruit': 'kiwi'}, ] for item in my_list.copy(): if item.get('id') == 2: my_list.remove(item) break # ๐Ÿ‘‡๏ธ [{'id': 1, 'fruit': 'apple'}, {'id': 3, 'fruit': 'kiwi'}] print(my_list)
On each iteration, we check if the current dictionary has an id key with a value of 2 and if the condition is met, we use the list.remove() method to remove it.

The dict.get() method returns the value for the given key if the key is in the dictionary, otherwise a default value is returned.

The method takes the following 2 parameters:

NameDescription
keyThe key for which to return the value
defaultThe default value to be returned if the provided key is not present in the dictionary (optional)
If a value for the default parameter is not provided, it defaults to None, so the get() method never raises a KeyError.

The list.remove() method removes the first item from the list whose value is equal to the passed-in argument.

The remove() method mutates the original list and returns None.

After we have found the dictionary to be removed, we use the break statement to break out of the for loop.

The break statement breaks out of the innermost enclosing for or while loop.

Using the break statement helps us avoid iterating needlessly after we've removed the dictionary from the list.

The most important thing to note when removing items from a list while iterating is to use the list.copy() method to iterate over a copy of the list.

If you try to remove elements from the original list while iterating over it, you might run into difficult-to-locate bugs.

Alternatively, you can use a list comprehension.

# Remove a dictionary from a list of dictionaries using list comprehension

This is a three-step process:

  1. Use a list comprehension to iterate over the list.
  2. Exclude the matching dictionary from the new list.
  3. The list comprehension will return a new list that doesn't contain the specified dictionary.
main.py
my_list = [ {'id': 1, 'fruit': 'apple'}, {'id': 2, 'fruit': 'banana'}, {'id': 3, 'fruit': 'kiwi'}, ] new_list = [ item for item in my_list if item.get('id') != 2 ] # ๐Ÿ‘‡๏ธ [{'id': 1, 'fruit': 'apple'}, {'id': 3, 'fruit': 'kiwi'}] print(new_list)

remove dictionary from list of dictionaries using list comprehension

The code for this article is available on GitHub

We used a list comprehension to iterate over the list of dictionaries.

List comprehensions are used to perform some operation for every element or select a subset of elements that meet a condition.

On each iteration, we check if the current dictionary doesn't have an id key with a value of 2 and return the result.

The new list contains the dictionaries that don't have an id key with a value of 2.

Using a list comprehension is more suitable if you have to remove one or more dictionaries from a list. The list comprehension keeps iterating after the first dictionary has been removed.

If you only have to remove a single dictionary from a list, use the for loop approach.

The list comprehension in the first example doesn't mutate the original list, it returns a new list.

# Remove a dictionary from a list of dictionaries using reassignment

If you want to change the contents of the original list, use list slicing.

main.py
my_list = [ {'id': 1, 'fruit': 'apple'}, {'id': 2, 'fruit': 'banana'}, {'id': 3, 'fruit': 'kiwi'}, ] my_list[:] = [ item for item in my_list if item.get('id') != 2 ] # ๐Ÿ‘‡๏ธ [{'id': 1, 'fruit': 'apple'}, {'id': 3, 'fruit': 'kiwi'}] print(my_list)

remove dictionary from list of dictionaries using reassignment

The code for this article is available on GitHub

We used the my_list[:] syntax to get a slice that represents the entire list, so we can assign to the variable directly.

main.py
my_list = [ {'id': 1, 'fruit': 'apple'}, {'id': 2, 'fruit': 'banana'}, {'id': 3, 'fruit': 'kiwi'}, ] # ๐Ÿ‘‡๏ธ [{'id': 1, 'fruit': 'apple'}, {'id': 2, 'fruit': 'banana'}, {'id': 3, 'fruit': 'kiwi'}] print(my_list[:])
The slice my_list[:] represents the entire list, so when we use it on the left-hand side, we are assigning to the entire list.

This approach changes the contents of the original list.

# Remove a dictionary from a list of dictionaries using filter()

You can also use the filter() function to remove a dictionary from a list of dictionaries.

main.py
my_list = [ {'id': 1, 'fruit': 'apple'}, {'id': 2, 'fruit': 'banana'}, {'id': 3, 'fruit': 'kiwi'}, ] new_list = list(filter( lambda dictionary: dictionary['id'] != 2, my_list )) # ๐Ÿ‘‡๏ธ [{'id': 1, 'fruit': 'apple'}, {'id': 3, 'fruit': 'kiwi'}] print(new_list)
The code for this article is available on GitHub

The filter() function takes a function and an iterable as arguments and constructs an iterator from the elements of the iterable for which the function returns a truthy value.

The lambda function we passed to filter gets called with each dictionary from the list.

The function checks if the id key of each dictionary is not equal to 2.

The filter object only contains the dictionaries that meet the condition.

The last step is to use the list() class to convert the filter object to a list.

# Remove empty dictionaries from a list of dicts in Python

Use a list comprehension to remove the empty dictionaries from a list of dictionaries.

The list comprehension will return a new list that doesn't contain any empty dictionaries.

main.py
# โœ… Remove empty dictionaries from a list (using list comprehension) list_of_dicts = [{'id': 1}, {}, {'id': 2}, {}, {'id': 3}] new_list = [item for item in list_of_dicts if item] print(new_list) # ๐Ÿ‘‰๏ธ [{'id': 1}, {'id': 2}, {'id': 3}] # --------------------------------------------- # โœ… Remove empty dictionaries from a list (using filter()) new_list = list(filter(None, list_of_dicts)) print(new_list) # ๐Ÿ‘‰๏ธ [{'id': 1}, {'id': 2}, {'id': 3}] # --------------------------------------------- # โœ… Remove empty dictionaries from a list (using for loop) for item in list_of_dicts.copy(): if item == {}: list_of_dicts.remove(item) print(list_of_dicts) # ๐Ÿ‘‰๏ธ [{'id': 1}, {'id': 2}, {'id': 3}]
The code for this article is available on GitHub

The first example uses a list comprehension to remove the empty dictionaries from a list of dictionaries.

List comprehensions are used to perform some operation for every element or select a subset of elements that meet a condition.
main.py
list_of_dicts = [{'id': 1}, {}, {'id': 2}, {}, {'id': 3}] new_list = [item for item in list_of_dicts if item] print(new_list) # ๐Ÿ‘‰๏ธ [{'id': 1}, {'id': 2}, {'id': 3}]

On each iteration, we check if the current item is truthy and return the result.

Empty dictionaries are falsy values, so they get filtered out.

The list comprehension creates a new list, it doesn't mutate the original list.

If you want to remove the empty dictionaries from the original list, use list slicing.

main.py
list_of_dicts = [{'id': 1}, {}, {'id': 2}, {}, {'id': 3}] list_of_dicts[:] = [item for item in list_of_dicts if item] print(list_of_dicts) # ๐Ÿ‘‰๏ธ [{'id': 1}, {'id': 2}, {'id': 3}]

We used the my_list[:] syntax to get a slice that represents the entire list, so we can assign to the variable directly.

The slice my_list[:] represents the entire list, so when we use it on the left-hand side, we are assigning to the entire list.

This approach changes the contents of the original list.

Alternatively, you can use the filter() function.

# Remove empty dictionaries from list of dicts using filter()

This is a three-step process:

  1. Use the filter() function to filter out the empty dictionaries.
  2. Use the list() class to convert the filter object to a list.
  3. The new list won't contain any empty lists.
main.py
list_of_dicts = [{'id': 1}, {}, {'id': 2}, {}, {'id': 3}] new_list = list(filter(None, list_of_dicts)) print(new_list) # ๐Ÿ‘‰๏ธ [{'id': 1}, {'id': 2}, {'id': 3}]
The code for this article is available on GitHub

We used the filter() function to remove the empty dictionaries from a list of dictionaries.

The filter() function takes a function and an iterable as arguments and constructs an iterator from the elements of the iterable for which the function returns a truthy value.

If you pass None for the function argument, all falsy elements of the iterable are removed.

An empty dictionary is a falsy value, so all empty dictionaries get removed.

The last step is to use the list() class to convert the filter object to a list.

Alternatively, you can use a for loop.

# Remove empty dictionaries from list of dicts using for loop

This is a three-step process:

  1. Use a for loop to iterate over a copy of the list.
  2. On each iteration, check if the current item is an empty dictionary.
  3. Use the list.remove() method to remove the empty dictionaries.
main.py
list_of_dicts = [{'id': 1}, {}, {'id': 2}, {}, {'id': 3}] for item in list_of_dicts.copy(): if item == {}: list_of_dicts.remove(item) print(list_of_dicts) # ๐Ÿ‘‰๏ธ [{'id': 1}, {'id': 2}, {'id': 3}]
The code for this article is available on GitHub
On each iteration, we check if the current item is an empty dictionary and use the list.remove() method to remove the matching elements.

The list.remove() method removes the first item from the list whose value is equal to the passed-in argument.

The remove() method mutates the original list and returns None.

The most important thing to note when removing items from a list in a for loop is to use the list.copy() method to iterate over a copy of the list.

If you try to iterate over the original list and remove items from it, you might run into difficult-to-locate bugs.

I've also written an article on how to remove the duplicates from a list of dictionaries.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.

Copyright ยฉ 2024 Borislav Hadzhiev