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}

Complete Series of Python Dictionary tutorials,

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}