Python : How to Remove multiple keys from Dictionary while Iterating ?

In this article we will discuss how to remove multiple key / value pairs from dictionary while iterating.

Suppose we have a dictionary of string and int i.e.

# Dictionary of strings
wordFreqDic = {
    "Hello": 51,
    "at" : 23 ,
    "test" : 33,
    "here" : 63,
    "start" : 13
    }

Now we want to remove all key/value pairs from dictionary whose value is divisible by 3. Let’s see how to do that,

Removing elements from Dictionary while Iterating

We can not change the size of dictionary while iterating over it. If we try to remove any element from dictionary while iterating over it then it will throw error.

For example,

for (key, value) in wordFreqDic.items() :
    if value % 3 == 0:
        del wordFreqDic[key]

Will through following Error, 

RuntimeError: dictionary changed size during iteration

So, let’s see how to delete multiple elements from dictionary.

Removing keys from dictionary while iterating by creating a list of keys

As we cannot iterate and remove elements from dictionary at same time. Therefore will, first iterate over the dictionary and create a list of keys that need to be deleted from dictionary.  Now, we will iterate over this list of keys and delete their entries from dictionary i.e.

'''
Removing multiple keys from dictionary by creating
a list of keys to be deleted and then deleting them one by one
'''

# List of keys to be deleted from dictionary
selectedKeys = list() 

# Iterate over the dict and put to be deleted keys in the list
for (key, value) in wordFreqDic.items() :
    if value % 3 == 0:
        selectedKeys.append(key)

# Iterate over the list and delete corresponding key from dictionary
for key in selectedKeys:
    if key in wordFreqDic :
        del wordFreqDic[key]

Now dictionary contents will be,

Modified Dictionary  {'start': 13, 'at': 23}

Removing keys from dictionary while iterating by creating a copy of dictionary

Create a copy of dictionary and iterate over this temporary dictionary, check element to be deleted and delete it from original dictionary i.e.

'''
Removing multiple keys from dictionary by creating
a copy of dictionary and iterating over it
'''

# Create a temporary copy of dictionary
copyOfDict = dict(wordFreqDic)

# Iterate over the temporary dictionary and delete corresponding key from original dictionary
for (key, value) in copyOfDict.items() :
    if value % 3 == 0:
        del wordFreqDic[key]

Now dictionary contents will be,

Modified Dictionary  {'start': 13, 'at': 23}

Python Dictionary Tutorial - Series:

  1. What is a Dictionary in Python & why do we need it?
  2. Creating Dictionaries in Python
  3. Iterating over dictionaries
  4. Check if a key exists in dictionary
  5. Check if a value exists in dictionary
  6. Get all the keys in Dictionary
  7. Get all the Values in a Dictionary
  8. Remove a key from Dictionary
  9. Add key/value pairs in Dictionary
  10. Find keys by value in Dictionary
  11. Filter a dictionary by conditions
  12. Print dictionary line by line
  13. Convert a list to dictionary
  14. Sort a Dictionary by key
  15. Sort a dictionary by value in descending or ascending order
  16. Dictionary: Shallow vs Deep Copy
  17. Remove keys while Iterating
  18. Get all keys with maximum value
  19. Merge two or more dictionaries in python

Subscribe with us to join a list of 2000+ programmers and get latest tips & tutorials at your inbox through our weekly newsletter.

 Complete example is as follows,

def main():
    
    # Dictionary of strings
    wordFreqDic = {
        "Hello": 51,
        "at" : 23 ,
        "test" : 33,
        "here" : 63,
        "start" : 13
        }
    
    print("Original Dictionary ", wordFreqDic)
    
    '''
    Removing multiple keys from dictionary by creating
    a list of keys to be deleted and then deleting them one by one
    '''
    
    # List of keys to be deleted from dictionary
    selectedKeys = list() 
    
    # Iterate over the dict and put to be deleted keys in the list
    for (key, value) in wordFreqDic.items() :
        if value % 3 == 0:
            selectedKeys.append(key)
    
    # Iterate over the list and delete corresponding key from dictionary
    for key in selectedKeys:
        if key in wordFreqDic :
            del wordFreqDic[key]        
            
    
    print("Modified Dictionary " , wordFreqDic)

    # Dictionary of strings
    wordFreqDic = {
        "Hello": 51,
        "at" : 23 ,
        "test" : 33,
        "here" : 63,
        "start" : 13
        }
    
    print("Original Dictionary ", wordFreqDic)

    '''
    Removing multiple keys from dictionary by creating
    a copy of dictionary and iterating over it
    '''
    
    # Create a temporary copy of dictionary
    copyOfDict = dict(wordFreqDic)
    
    # Iterate over the temporary dictionary and delete corresponding key from original dictionary
    for (key, value) in copyOfDict.items() :
        if value % 3 == 0:
            del wordFreqDic[key]
    
    print("Modified Dictionary ", wordFreqDic)
     
           
if __name__ == '__main__':
    main()

Output:

Original Dictionary  {'Hello': 51, 'test': 33, 'here': 63, 'start': 13, 'at': 23}
Modified Dictionary  {'start': 13, 'at': 23}
Original Dictionary  {'Hello': 51, 'test': 33, 'here': 63, 'start': 13, 'at': 23}
Modified Dictionary  {'start': 13, 'at': 23}

 

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top