Last updated: Apr 9, 2024
Reading timeยท7 min
To remove a dictionary from a list of dictionaries:
for
loop to iterate over a copy of the list.list.remove()
method to remove the matching dictionary from the
list.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)
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.
However, we can iterate over a copy of the list and remove elements from the original list.
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)
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:
Name | Description |
---|---|
key | The key for which to return the value |
default | The default value to be returned if the provided key is not present in the dictionary (optional) |
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.
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.
This is a three-step process:
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)
We used a list comprehension to iterate over the list of dictionaries.
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
.
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.
If you want to change the contents of the original list, use list slicing.
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)
We used the my_list[:]
syntax to get a slice that represents the entire list,
so we can assign to the variable directly.
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[:])
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.
You can also use the filter()
function to remove a dictionary from a list of
dictionaries.
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 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.
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.
# โ 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 first example uses a list comprehension to remove the empty dictionaries from a list of dictionaries.
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.
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.
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.
This is a three-step process:
filter()
function to filter out the empty dictionaries.list()
class to convert the filter
object to a list.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}]
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.
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.
This is a three-step process:
for
loop to iterate over a copy of the list.list.remove()
method to remove the empty dictionaries.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}]
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.
You can learn more about the related topics by checking out the following tutorials: