Python | Delete items from dictionary while iterating
Last Updated :
13 Mar, 2023
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
myDict = { 1 : 'Geeks' , 2 : 'For' , 3 : 'Geeks' }
for key in myDict.keys():
if key = = 2 :
del myDict[key]
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
myDict = { 1 : 'Geeks' , 2 : 'For' , 3 : 'Geeks' }
delete = [key for key in myDict if key = = 3 ]
for key in delete:
del myDict[key]
print (myDict)
|
Output:
{1: 'Geeks', 2: 'For'}
Method 3: 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
myDict = { 1 : 'Geeks' , 2 : 'For' , 3 : 'Geeks' }
delete = []
for key in myDict:
if key = = 3 :
delete.append(key)
for i in delete:
del myDict[i]
print (myDict)
|
Output
{1: 'Geeks', 2: 'For'}
Method 4: Using list(myDict)
Python3
myDict = { 1 : 'Geeks' , 2 : 'For' , 3 : 'Geeks' }
for key in list (myDict):
if key = = 2 :
del myDict[key]
print (myDict)
|
Output:
{1: 'Geeks', 3: 'Geeks'}
Method 5: Using the pop() method with the key as an argument
The pop() method removes the key-value pair for the given key and returns the corresponding value. Since we don’t need the value in this case, we can simply pass the key as an argument and it will remove the key-value pair from the dictionary.
Python3
myDict = { 1 : 'Geeks' , 2 : 'For' , 3 : 'Geeks' }
myDict.pop( 2 )
print (myDict)
|
Output
{1: 'Geeks', 3: 'Geeks'}
Time complexity: O(1) for removing the key-value pair using pop() method.
Auxiliary space: O(1) as it doesn’t use any additional data structure.
Please Login to comment...