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:
- What is a Dictionary in Python & why do we need it?
- Creating Dictionaries in Python
- Iterating over dictionaries
- Check if a key exists in dictionary
- Check if a value exists in dictionary
- Get all the keys in Dictionary
- Get all the Values in a Dictionary
- Remove a key from Dictionary
- Add key/value pairs in Dictionary
- Find keys by value in Dictionary
- Filter a dictionary by conditions
- Print dictionary line by line
- Convert a list to dictionary
- Sort a Dictionary by key
- Sort a dictionary by value in descending or ascending order
- Dictionary: Shallow vs Deep Copy
- Remove keys while Iterating
- Get all keys with maximum value
- 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}
Pandas Tutorials -Learn Data Analysis with Python
-
Pandas Tutorial Part #1 - Introduction to Data Analysis with Python
-
Pandas Tutorial Part #2 - Basics of Pandas Series
-
Pandas Tutorial Part #3 - Get & Set Series values
-
Pandas Tutorial Part #4 - Attributes & methods of Pandas Series
-
Pandas Tutorial Part #5 - Add or Remove Pandas Series elements
-
Pandas Tutorial Part #6 - Introduction to DataFrame
-
Pandas Tutorial Part #7 - DataFrame.loc[] - Select Rows / Columns by Indexing
-
Pandas Tutorial Part #8 - DataFrame.iloc[] - Select Rows / Columns by Label Names
-
Pandas Tutorial Part #9 - Filter DataFrame Rows
-
Pandas Tutorial Part #10 - Add/Remove DataFrame Rows & Columns
-
Pandas Tutorial Part #11 - DataFrame attributes & methods
-
Pandas Tutorial Part #12 - Handling Missing Data or NaN values
-
Pandas Tutorial Part #13 - Iterate over Rows & Columns of DataFrame
-
Pandas Tutorial Part #14 - Sorting DataFrame by Rows or Columns
-
Pandas Tutorial Part #15 - Merging or Concatenating DataFrames
-
Pandas Tutorial Part #16 - DataFrame GroupBy explained with examples
Are you looking to make a career in Data Science with Python?
Data Science is the future, and the future is here now. Data Scientists are now the most sought-after professionals today. To become a good Data Scientist or to make a career switch in Data Science one must possess the right skill set. We have curated a list of Best Professional Certificate in Data Science with Python. These courses will teach you the programming tools for Data Science like Pandas, NumPy, Matplotlib, Seaborn and how to use these libraries to implement Machine learning models.
Checkout the Detailed Review of Best Professional Certificate in Data Science with Python.
Remember, Data Science requires a lot of patience, persistence, and practice. So, start learning today.