Python: Delete items from Dictionary while iterating over it

avatar

Borislav Hadzhiev

Last updated: Sep 20, 2022

banner

Photo from Unsplash

Python: Delete items from Dictionary while iterating over it #

To delete items from a dictionary while iterating over it:

  1. Use the dict.copy() method to iterate over a copy of the dictionary.
  2. On each iteration, check if a condition is met.
  3. Use the del operator to delete the matching items.
main.py
my_dict = { 'first_name': 'bobby', 'last_name': 'hadz', 'site': 'bobbyhadz.com', 'topic': 'Python' } for key in my_dict.copy(): if my_dict[key] == 'bobby': del my_dict[key] # 👇️ {'last_name': 'hadz', 'site': 'bobbyhadz.com', 'topic': 'Python'} print(my_dict)

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

The dict.copy method returns a shallow copy of the object on which the method was called.

This is necessary because we aren't allowed to modify a dictionary's items while iterating over it.

However, we can iterate over a copy of the dictionary and modify the items of the original dictionary.

On each iteration, we check if the current value is equal to a specific string.

If the condition is met, we use the del operator to remove the key-value pair from the dictionary.

We could also use the dict.items() method to achieve the same result.

main.py
my_dict = { 'first_name': 'bobby', 'last_name': 'hadz', 'site': 'bobbyhadz.com', 'topic': 'Python' } for key, value in my_dict.copy().items(): if value == 'bobby': del my_dict[key] # 👇️ {'last_name': 'hadz', 'site': 'bobbyhadz.com', 'topic': 'Python'} print(my_dict)

The dict.items method returns a new view of the dictionary's items ((key, value) pairs).

main.py
my_dict = {'id': 1, 'name': 'BobbyHadz'} # 👇️ dict_items([('id', 1), ('name', 'BobbyHadz')]) print(my_dict.items())

Alternatively, you can use the list() class.

Delete items from Dictionary while iterating over it using list() #

To delete items from a dictionary while iterating over it:

  1. Use the list() class to convert the dictionary to a list of keys.
  2. Use a for loop to iterate over the list of keys.
  3. Use the del operator to delete the items for which a certain condition is met.
main.py
my_dict = { 'first_name': 'bobby', 'last_name': 'hadz', 'site': 'bobbyhadz.com', 'topic': 'Python' } for key in list(my_dict): if my_dict[key] == 'bobby': del my_dict[key] # 👇️ {'last_name': 'hadz', 'site': 'bobbyhadz.com', 'topic': 'Python'} print(my_dict)

We used the list() class to convert the dictionary to a list of keys.

main.py
my_dict = { 'first_name': 'bobby', 'last_name': 'hadz', 'site': 'bobbyhadz.com', 'topic': 'Python' } # 👇️ ['first_name', 'last_name', 'site', 'topic'] print(list(my_dict))

Instead of iterating over the dictionary, we iterate over the list of keys.

On each iteration, we check if a condition is met and delete the matching keys.

Alternatively, you can use a dict comprehension.

Delete items from Dictionary while iterating over it using dict comprehension #

To delete items from a dictionary while iterating over it:

  1. Use a dict comprehension to iterate over the dictionary's items.
  2. Check if a condition is met and return the result.
  3. The new dictionary won't contain any of the items that don't meet the condition.
main.py
my_dict = { 'first_name': 'bobby', 'last_name': 'hadz', 'site': 'bobbyhadz.com', 'topic': 'Python' } new_dict = { key: value for key, value in my_dict.items() if value != 'bobby' } # 👇️ {'last_name': 'hadz', 'site': 'bobbyhadz.com', 'topic': 'Python'} print(new_dict)

We used a dict comprehension to iterate over the dictionary's items.

Dict comprehensions are very similar to list comprehensions.

They perform some operation for every key-value pair in the dictionary or select a subset of key-value pairs that meet a condition.

On each iteration, we check if the current value is not equal to a specific string and return the result.

The new dictionary won't contain any of the items that don't meet the condition.

Note that this approach doesn't remove key-value pairs from the original dictionary, it returns a new dictionary.

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.