Python | Delete items from dictionary while iterating
Last Updated :
13 Mar, 2023
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.
Similar Reads
How to Compare Two Dictionaries in Python In this article, we will discuss how to compare two dictionaries in Python. The simplest way to compare two dictionaries for equality is by using the == operator.Using == operatorThis operator checks if both dictionaries have the same keys and values.Pythond1 = {'a': 1, 'b': 2} d2 = {'a': 1, 'b': 2}
2 min read
Python Dictionary Comprehension Like List Comprehension, Python allows dictionary comprehensions. We can create dictionaries using simple expressions. A dictionary comprehension takes the form {key: value for (key, value) in iterable}Python Dictionary Comprehension ExampleHere we have two lists named keys and value and we are iter
4 min read
How to Add Values to Dictionary in Python The task of adding values to a dictionary in Python involves inserting new key-value pairs or modifying existing ones. A dictionary stores data in key-value pairs, where each key must be unique. Adding values allows us to expand or update the dictionary's contents, enabling dynamic manipulation of d
3 min read
Add new keys to a dictionary in Python In this article, we will explore various methods to add new keys to a dictionary in Python. Let's explore them with examples:Using Assignment Operator (=)The simplest way to add a new key is by using assignment operator (=).Pythond = {"a": 1, "b": 2} d["c"] = 3 print(d)Output{'a': 1, 'b': 2, 'c': 3}
2 min read
Add Item after Given Key in Dictionary - Python The task of adding an item after a specific key in a Pythondictionary involves modifying the order of the dictionary's key-value pairs. Since Python dictionaries maintain the insertion order, we can achieve this by carefully placing the new key-value pair after the target key. For example, consider
4 min read
Python - Ways to remove a key from dictionary We are given a dictionary and our task is to remove a specific key from it. For example, if we have the dictionary d = {"a": 1, "b": 2, "c": 3}, then after removing the key "b", the output will be {'a': 1, 'c': 3}.Using pop()pop() method removes a specific key from the dictionary and returns its cor
3 min read
Removing Dictionary from List of Dictionaries - Python We are given a list of dictionaries, and our task is to remove specific dictionaries based on a condition. For instance given the list: a = [{'x': 10, 'y': 20}, {'x': 30, 'y': 40}, {'x': 50, 'y': 60}], we might want to remove the dictionary where 'x' equals 30 then the output will be [{'x': 10, 'y':
3 min read
Python - Remove item from dictionary when key is unknown We are given a dictionary we need to remove the item or the value of key which is unknown. For example, we are given a dictionary a = {'a': 10, 'b': 20, 'c': 30} we need to remove the key 'b' so that the output dictionary becomes like {'a': 10, 'c': 30} . To do this we can use various method and app
4 min read
Python - Test if all Values are Same in Dictionary Given a dictionary, test if all its values are the same. Input : test_dict = {"Gfg" : 8, "is" : 8, "Best" : 8} Output : True Explanation : All element values are same, 8. Input : test_dict = {"Gfg" : 8, "is" : 8, "Best" : 9} Output : False Explanation : All element values not same. Method #1: Using
7 min read
Python | Test if element is dictionary value Sometimes, while working with a Python dictionary, we have a specific use case in which we just need to find if a particular value is present in the dictionary as it's any key's value. This can have use cases in any field of programming one can think of. Let's discuss certain ways in which this prob
4 min read