Open In App

Python | Delete items from dictionary while iterating

Last Updated : 13 Mar, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

A dictionary in Python is an ordered collection of data values. Unlike other Data Types that hold only a single value as an element, a dictionary holds the key: value pairs. Dictionary keys must be unique and must be of an immutable data type such as a: string, integer or tuple.

Note: In Python 2 dictionary keys were unordered. As of Python 3, they are ordered.

Let’s see how to delete items from a dictionary while iterating over it. 

Method 1: Using del() method

Python3




# Creating a dictionary
myDict = {1: 'Geeks', 2: 'For', 3: 'Geeks'}
 
# Iterating through the keys
for key in myDict.keys():
    if key == 2:
        del myDict[key]
 
# Modified Dictionary
print(myDict)


Output:

{1: 'Geeks', 3: 'Geeks'}

The above code works fine for Python2, (as in that version dictionary keys were unordered). But if we run it with Python3, it throws the following error:  

for key in myDict.keys():
RuntimeError: dictionary changed size during iteration

This runtime error says changing the size of the dictionary during iteration is not allowed (but it is possible). Now, let’s see all the different ways we can delete items from the dictionary while iterating. 

Method 2: Creating a List of Keys to delete

Here we use a list comprehension to build a list of all the keys that need to be deleted and then iterate through each key in that list deleting them:

Python3




# Creating a dictionary
myDict = {1: 'Geeks', 2: 'For', 3: 'Geeks'}
 
# Using a list comprehension to make a list of the keys to be deleted
# (keys having value in 3.)
delete = [key for key in myDict if key == 3]
 
# delete the key/s
for key in delete:
    del myDict[key]
 
# Modified Dictionary
print(myDict)


Output: 

{1: 'Geeks', 2: 'For'}

Method 3: Or if you’re new to list comprehensions:

We can build up the list of keys to delete using a for loop for that do create a list delete and add keys of all the values we want to delete. 

Python




# Creating a dictionary
myDict = {1: 'Geeks', 2: 'For', 3: 'Geeks'}
 
# create a list of keys to delete
delete = []
for key in myDict:
    if key == 3:
        delete.append(key)
 
for i in delete:
    del myDict[i]
 
# Modified Dictionary
print(myDict)


Output

{1: 'Geeks', 2: 'For'}

Method 4: Using list(myDict) 

Python3




# Creating a dictionary
myDict = {1: 'Geeks', 2: 'For', 3: 'Geeks'}
 
# Iterating through the list of keys
for key in list(myDict):
    if key == 2:
        del myDict[key]
 
# Modified Dictionary
print(myDict)


Output: 

{1: 'Geeks', 3: 'Geeks'}

Method 5: Using the pop() method with the key as an argument

The pop() method removes the key-value pair for the given key and returns the corresponding value. Since we don’t need the value in this case, we can simply pass the key as an argument and it will remove the key-value pair from the dictionary.

Python3




# Creating a dictionary
myDict = {1: 'Geeks', 2: 'For', 3: 'Geeks'}
 
# Removing the key-value pair for key 2
myDict.pop(2)
 
# Modified Dictionary
print(myDict)


Output

{1: 'Geeks', 3: 'Geeks'}

Time complexity: O(1) for removing the key-value pair using pop() method. 
Auxiliary space: O(1) as it doesn’t use any additional data structure.



Previous Article
Next Article

Similar Reads

Why is iterating over a dictionary slow in Python?
In this article, we are going to discuss why is iterating over a dict so slow in Python? Before coming to any conclusion lets have a look at the performance difference between NumPy arrays and dictionaries in python: Python Code # import modules import numpy as np import sys # compute numpy performance def np_performance(): array = np.empty(1000000
3 min read
Python: Iterating With Python Lambda
In Python, the lambda function is an anonymous function. This one expression is evaluated and returned. Thus, We can use lambda functions as a function object. In this article, we will learn how to iterate with lambda in python. Syntax: lambda variable : expression Where, variable is used in the expressionexpression can be an mathematical expressio
2 min read
Python Program to find the profit or loss when CP of N items is equal to SP of M items
Given [Tex]N   [/Tex]and [Tex]M   [/Tex]denoting that the Cost Price of N articles is equal to the Selling Price of M articles. The task is to determine the profit or Loss percentage. Examples:  Input: N = 8, M = 9 Output: Loss = -11.11% Input: N = 8, M = 5 Output: Profit = 60% Formula:-  Below is the implementation of the above approach: C/C++ Cod
1 min read
Python | Iterating two lists at once
Sometimes, while working with Python list, we can have a problem in which we have to iterate over two list elements. Iterating one after another is an option, but it's more cumbersome and a one-two liner is always recommended over that. Let's discuss certain ways in which this task can be performed. Method #1 : Using loop + "+" operator The combina
5 min read
Python - Iterating through a range of dates
In this article, we will discuss how to iterate DateTime through a range of dates. Using loop and timedelta to Iterate through a range of dates Timedelta is used to get the dates and loop is to iterate the date from the start date to end date Syntax: delta = datetime.timedelta(days=1) Example: Python code to display the dates from 2021 - Feb 1st to
2 min read
Iterating List of Python Dictionaries
Iteration of the list of dictionaries is a very common practice that every developer performs while encountering with dictionary data. In this article, we will explore how to iterate through a list of dictionaries. Iterating List Of Dictionaries in PythonBelow are some of the ways by which we can iterate list of dictionaries in Python: Using a simp
3 min read
MoviePy – Iterating frames of Video File Clip
In this article we will see how we can iterate frames of the video file clip in MoviePy. MoviePy is a Python module for video editing, which can be used for basic operations on videos and GIF’s. A video is basically combination of lots of frame for each time there is a specific frame, in order to get the frame at given time we use get_frame method.
2 min read
Iterating over rows and columns in Pandas DataFrame
Iteration is a general term for taking each item of something, one after another. Pandas DataFrame consists of rows and columns so, to iterate over dataframe, we have to iterate a dataframe like a dictionary. In a dictionary, we iterate over the keys of the object in the same way we have to iterate in dataframe. In this article, we are using "nba.c
6 min read
Python Dictionary items() method
Dictionary in Python is an unordered collection of data values, used to store data values like a map, which unlike other Data Types that hold only single value as an element, Dictionary holds key : value pair.In Python Dictionary, items() method is used to return the list with all dictionary keys with values. Syntax: dictionary.items()Parameters: T
2 min read
Python program to find the sum of all items in a dictionary
Given a dictionary in Python, write a Python program to find the sum of all items in the dictionary. Examples: Input : {'a': 100, 'b':200, 'c':300}Output : 600 Input : {'x': 25, 'y':18, 'z':45}Output : 88 Method #1: Using Inbuilt sum() Function Use the sum function to find the sum of dictionary values. C/C++ Code # Python3 Program to find sum of #
6 min read