Skip to content
Related Articles

Related Articles

Python | Delete items from dictionary while iterating

View Discussion
Improve Article
Save Article
Like Article
  • Last Updated : 16 May, 2022

A dictionary in Python is an ordered collection of data values. Unlike other Data Types that hold only a single value as an element, a dictionary holds the key: value pairs. Dictionary keys must be unique and must be of an immutable data type such as a: string, integer or tuple.

Note: In Python 2 dictionary keys were unordered. As of Python 3, they are ordered.

Let’s see how to delete items from a dictionary while iterating over it. 

Method #1: Using del() method  

Python3




# Creating a dictionary
myDict = {1: 'Geeks', 2: 'For', 3: 'Geeks'}
 
# Iterating through the keys
for key in myDict.keys():
    if key == 2:
        del myDict[key]
 
# Modified Dictionary
print(myDict)

Output:

{1: 'Geeks', 3: 'Geeks'}

The above code works fine for Python2, (as in that version dictionary keys were unordered). But if we run it with Python3, it throws the following error:  

for key in myDict.keys():
RuntimeError: dictionary changed size during iteration

This runtime error says changing the size of the dictionary during iteration is not allowed (but it is possible). Now, let’s see all the different ways we can delete items from the dictionary while iterating. 

Method #2: Creating a List of Keys to delete

Here we use a list comprehension to build a list of all the keys that need to be deleted and then iterate through each key in that list deleting them:

Python3




# Creating a dictionary
myDict = {1: 'Geeks', 2: 'For', 3: 'Geeks'}
 
# Using a list comprehension to make a list of the keys to be deleted
# (keys having value in 3.)
delete = [key for key in myDict if key == 3]
 
# delete the key/s
for key in delete:
    del myDict[key]
 
# Modified Dictionary
print(myDict)

Output: 

{1: 'Geeks', 2: 'For'}

Or if you’re new to list comprehensions:

We can build up the list of keys to delete using a for loop for that do create a list delete and add keys of all the values we want to delete. 

Python




# Creating a dictionary
myDict = {1: 'Geeks', 2: 'For', 3: 'Geeks'}
 
# create a list of keys to delete
delete = []
for key in myDict:
    if key == 3:
        delete.append(key)
 
for i in delete:
    del myDict[i]
 
# Modified Dictionary
print(myDict)

Method #3: Using list(myDict) 
 

Python3




# Creating a dictionary
myDict = {1: 'Geeks', 2: 'For', 3: 'Geeks'}
 
# Iterating through the list of keys
for key in list(myDict):
    if key == 2:
        del myDict[key]
 
# Modified Dictionary
print(myDict)

Output: 

{1: 'Geeks', 3: 'Geeks'}


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!