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.

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,

Will through following Error, 

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.

Now dictionary contents will be,

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.

Now dictionary contents will be,

 Complete example is as follows,

Output:

 

Click Here to Subscribe for more Articles / Tutorials like this.