Delete items from dictionary while iterating in Python


A python dictionary is a collection which is unordered, changeable and indexed. They have keys and values and each item is referred using the key. In this article we will explore the ways to delete the items form a dictionary.

Using del with keys

In this approach we capture the key values that are needed to be deleted. Once we apply the del function, the key value pairs for those keys get deleted.

Example

 Live Demo

# Given dictionary
ADict = {1: 'Mon', 2: 'Tue', 3: 'Wed',4:'Thu',5:'Fri'}

# Get keys with value in 2,3.
to_del = [key for key in ADict if key in(2,3)]

# Delete keys
for key in to_del: del ADict[key]

# New Dictionary
print(ADict)

Output

Running the above code gives us the following result −

{1: 'Mon', 4: 'Thu', 5: 'Fri'}

Using list with keys

We can create a list containing the keys from the dictionary and also use a conditional expression to select the keys to be used for deletion. In the below example we have only considered the keys with even values by comparing the remainder from division with two equal to zero.

Example

 Live Demo

# Given dictionary
ADict = {1: 'Mon', 2: 'Tue', 3: 'Wed',4:'Thu',5:'Fri'}

# Get keys with even value
for key in list(ADict):
if (key%2) == 0:
del ADict[key]

# New Dictionary
print(ADict)

Output

Running the above code gives us the following result −

{1: 'Mon', 3: 'Wed', 5: 'Fri'}

Using items to Delete

Instead of keys we can also use the items of the dictionary to delete the values. But after choosing the item we have to indirectly use the keys to select the items to be deleted.

Example

 Live Demo

# Given dictionary
ADict = {1: 'Mon', 2: 'Tue', 3: 'Wed',4:'Thu',5:'Fri'}

NewDict = []
# Get keys with even value
for key,val in ADict.items():
if val in('Tue','Fri'):
NewDict.append(key)

for i in NewDict:
del ADict[i]

# New Dictionary
print(ADict)

Output

Running the above code gives us the following result −

{1: 'Mon', 3: 'Wed', 4: 'Thu'}

Updated on: 04-May-2020

376 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements