In this article, we will discuss different ways to delete key-value pairs from a dictionary while iterating over it.

Table of Contents

Can you actually change the size of dictionary during iteration in Python?

Issue in deleting items from dictionary while iterating [Problem]

Dictionary changed size during iteration in python

If you are planning to iterate over dictionary using a for loop and want to delete elements while iteration. Then you can not just call the dictionary’s pop() function or del keyword during the for loop because dictionary size can not change while iteration and if you will try to do that then it will give error. Checkout this example,

# Dictionary of string and integers
word_freq = {
    'Hello' : 56,
    'at'    : 23,
    'test'  : 43,
    'This'  : 78,
    'Why'   : 11
}

# Wrong way to delete an item from dictionary while iteration 
# RuntimeError: dictionary changed size during iteration
for key, value in word_freq.items():
    if value == 23:
        del word_freq[key]

print(word_freq)

This code will following error,

Traceback (most recent call last):
  File ".\iterate_delete.py", line 16, in <module>
    for key, value in word_freq.items():
RuntimeError: dictionary changed size during iteration

It gave the RuntimeError, because we can not change the size of dictionary while iteration. So, to delete key-value pairs from dictionary we need to create a copy of dictionary first. Let’s see how to do that,

Remove key-value pairs from dictionary during Iteration [Solved]

We can create a copy of dictionary and iterate over that and delete elements from original dictionary while iteration. For example, we have a dictionary of string and integers. We want to delete all iterate over this dictionary and delete items where value is matching a given value. Let’s see how to do that,

# Dictionary of string and integers
word_freq = {
    'Hello' : 56,
    'at'    : 23,
    'test'  : 43,
    'This'  : 78,
    'Why'   : 11
}

# Delete an item from dictionary while iteration 
for key, value in dict(word_freq).items():
    if value == 23:
        del word_freq[key]

print(word_freq)

Output:

{'Hello': 56,
 'test': 43,
 'This': 78,
 'Why': 11}

We created a copy of original dictionary word_freq and iterated over all key-value pairs of this dictionary copy. Then during iteration, for each key-value pair we checked if value is 23 or not. if yes, then we deleted the pair from original dictionary word_freq. It gave an effect that we have deleted elements from dictionary during iteration.

Let’s checkout another example,

Iterate over a dictionary and remove items with even values

# Dictionary of string and integers
word_freq = {
    'Hello' : 56,
    'at'    : 23,
    'test'  : 43,
    'This'  : 78,
    'Why'   : 11
}

# Delete items from dictionary while iterating
# and based on conditions on values
for key, value in dict(word_freq).items():
    if value % 2 == 0:
        del word_freq[key]

print(word_freq)

Output:

{'at': 23, 
'test': 43, 
'Why': 11}

Delete items from dictionary while iterating using comprehension

We can use dictionary comprehension to filter items from a dictionary based on condition and assign back the new dictionary to original reference variable. For example,

Iterate over a dictionary and remove items with even values

# Dictionary of string and integers
word_freq = {
    'Hello' : 56,
    'at'    : 23,
    'test'  : 43,
    'This'  : 78,
    'Why'   : 11
}

# Delete items from dictionary while iterating using comprehension
# and based on conditions on values
word_freq = {   key: value 
                for key, value in word_freq.items()
                if value % 2 != 0}

print(word_freq)

Output:

{'at': 23, 
'test': 43, 
'Why': 11}

Here we iterated over all key-value pairs of dictionary and created a new dictionary with only those items where value is not even. Then we assigned this new dictionary to original reference variable. It gave an effect that we have deleted items from dictionary where value is even.

Iterate over a dictionary and remove items using pop() function

Just like the first solution, we can create a copy of original dictionary and iterate over it. During iteration we can apply a condition on each pair and if condition is satisfied then we can delete that element from original dictionary. But here we will use pop() function instead of del keyword to delete elements during iteration. For example,

# Dictionary of string and integers
word_freq = {
    'Hello' : 56,
    'at'    : 23,
    'test'  : 43,
    'This'  : 78,
    'Why'   : 11
}

for key in dict(word_freq):
    if word_freq[key] % 2 == 0:
        word_freq.pop(key)

print(word_freq)

Output:

{'at': 23, 
'test': 43, 
'Why': 11}

Here we iterated over all key-value pairs of dictionary and during iteration deleted items where value is even.

Pro Tip:
pop() function accepts a key and a default value as arguments. If key is present in the dictionary, then it deletes that. Also, it returns,

  • The value of deleted item if key exist in dictionary.
  • The default value if key doesn’t exist in the dictionary.
  • KeyError if key does not exist in the dictionary and default value is also not provided.

Summary:

We learned different ways to delete key-value pairs from dictionary during iteration.