I have a dictionary of lists in which some of the values are empty:
d = {'a': [1], 'b': [1, 2], 'c': [], 'd':[]}
At the end of creating these lists, I want to remove these empty lists before returning my dictionary. I tried doing it like this:
for i in d:
if not d[i]:
d.pop(i)
but I got a RuntimeError. I am aware that you cannot add/remove elements in a dictionary while iterating through it…what would be a way around this then?
See Modifying a Python dict while iterating over it for citations that this can cause problems, and why.
asked Aug 13, 2012 at 20:30
user1530318user1530318
24.3k15 gold badges36 silver badges48 bronze badges
1
In Python 3.x and 2.x you can use use list to force a copy of the keys to be made:
for i in list(d):
In Python 2.x calling keys made a copy of the keys that you could iterate over while modifying the dict:
for i in d.keys():
But note that in Python 3.x this second method doesn’t help with your error because keys returns an a view object instead of copying the keys into a list.
evandrix
5,9864 gold badges27 silver badges37 bronze badges
answered Aug 13, 2012 at 20:33
Mark ByersMark Byers
795k188 gold badges1562 silver badges1443 bronze badges
7
You only need to use copy:
This way you iterate over the original dictionary fields and on the fly can change the desired dict d.
It works on each Python version, so it’s more clear.
In [1]: d = {'a': [1], 'b': [1, 2], 'c': [], 'd':[]}
In [2]: for i in d.copy():
...: if not d[i]:
...: d.pop(i)
...:
In [3]: d
Out[3]: {'a': [1], 'b': [1, 2]}
(BTW — Generally to iterate over copy of your data structure, instead of using .copy for dictionaries or slicing [:] for lists, you can use import copy -> copy.copy (for shallow copy which is equivalent to copy that is supported by dictionaries or slicing [:] that is supported by lists) or copy.deepcopy on your data structure.)
mkrieger1
16.9k4 gold badges51 silver badges58 bronze badges
answered Mar 31, 2016 at 10:35
1
Just use dictionary comprehension to copy the relevant items into a new dict:
>>> d
{'a': [1], 'c': [], 'b': [1, 2], 'd': []}
>>> d = {k: v for k, v in d.items() if v}
>>> d
{'a': [1], 'b': [1, 2]}
For this in Python 2:
>>> d
{'a': [1], 'c': [], 'b': [1, 2], 'd': []}
>>> d = {k: v for k, v in d.iteritems() if v}
>>> d
{'a': [1], 'b': [1, 2]}
answered Aug 13, 2012 at 20:38
Maria ZverinaMaria Zverina
10.6k3 gold badges43 silver badges61 bronze badges
3
This worked for me:
d = {1: 'a', 2: '', 3: 'b', 4: '', 5: '', 6: 'c'}
for key, value in list(d.items()):
if value == '':
del d[key]
print(d)
# {1: 'a', 3: 'b', 6: 'c'}
Casting the dictionary items to list creates a list of its items, so you can iterate over it and avoid the RuntimeError.
wjandrea
26.2k8 gold badges57 silver badges78 bronze badges
answered Jan 31, 2020 at 9:05
singriumsingrium
2,5545 gold badges29 silver badges42 bronze badges
0
I would try to avoid inserting empty lists in the first place, but, would generally use:
d = {k: v for k,v in d.iteritems() if v} # re-bind to non-empty
If prior to 2.7:
d = dict( (k, v) for k,v in d.iteritems() if v )
or just:
empty_key_vals = list(k for k in k,v in d.iteritems() if v)
for k in empty_key_vals:
del[k]
answered Aug 13, 2012 at 20:42
Jon ClementsJon Clements
137k32 gold badges243 silver badges277 bronze badges
5
For Python 3:
{k:v for k,v in d.items() if v}
Ahmad
2273 silver badges15 bronze badges
answered Jan 14, 2016 at 16:14
ucyoucyo
6177 silver badges16 bronze badges
1
To avoid «dictionary changed size during iteration error».
For example: «when you try to delete some key»,
Just use ‘list’ with ‘.items()’. Here is a simple example:
my_dict = {
'k1':1,
'k2':2,
'k3':3,
'k4':4
}
print(my_dict)
for key, val in list(my_dict.items()):
if val == 2 or val == 4:
my_dict.pop(key)
print(my_dict)
Output:
{'k1': 1, 'k2': 2, 'k3': 3, 'k4': 4}
{'k1': 1, 'k3': 3}
This is just an example. Change it based on your case/requirements.
answered Mar 19, 2021 at 22:59
K.AK.A
1,0689 silver badges21 bronze badges
You cannot iterate through a dictionary while it’s changing during a for loop. Make a casting to list and iterate over that list. It works for me.
for key in list(d):
if not d[key]:
d.pop(key)
answered May 17, 2019 at 9:28
Python 3 does not allow deletion while iterating (using the for loop above) a dictionary. There are various alternatives to do it; one simple way is to change the line
for i in x.keys():
with
for i in list(x)
answered Dec 26, 2019 at 22:23
Hasham BeygHasham Beyg
3153 silver badges11 bronze badges
0
The reason for the runtime error is that you cannot iterate through a data structure while its structure is changing during iteration.
One way to achieve what you are looking for is to use a list to append the keys you want to remove and then use the pop function on dictionary to remove the identified key while iterating through the list.
d = {'a': [1], 'b': [1, 2], 'c': [], 'd':[]}
pop_list = []
for i in d:
if not d[i]:
pop_list.append(i)
for x in pop_list:
d.pop(x)
print (d)
answered Oct 6, 2018 at 21:00
RohitRohit
173 bronze badges
For situations like this, I like to make a deep copy and loop through that copy while modifying the original dict.
If the lookup field is within a list, you can enumerate in the for loop of the list and then specify the position as the index to access the field in the original dict.
answered Oct 30, 2018 at 20:41
0
Nested null values
Let’s say we have a dictionary with nested keys, some of which are null values:
dicti = {
"k0_l0":{
"k0_l1": {
"k0_l2": {
"k0_0":None,
"k1_1":1,
"k2_2":2.2
}
},
"k1_l1":None,
"k2_l1":"not none",
"k3_l1":[]
},
"k1_l0":"l0"
}
Then we can remove the null values using this function:
def pop_nested_nulls(dicti):
for k in list(dicti):
if isinstance(dicti[k], dict):
dicti[k] = pop_nested_nulls(dicti[k])
elif not dicti[k]:
dicti.pop(k)
return dicti
Output for pop_nested_nulls(dicti)
{'k0_l0': {'k0_l1': {'k0_l2': {'k1_1': 1,
'k2_2': 2.2}},
'k2_l1': 'not '
'none'},
'k1_l0': 'l0'}
answered Jan 19 at 13:54
Echo9kEcho9k
4765 silver badges9 bronze badges
-
The Python «RuntimeError: dictionary changed size during iteration» occurs when we change the size of a dictionary when iterating over it.
-
To solve the error, use the copy() method to create a shallow copy of the dictionary that you can iterate over, e.g.,
my_dict.copy().my_dict = {'a': 1, 'b': 2, 'c': 3} for key in my_dict.copy(): print(key) if key == 'b': del my_dict[key] print(my_dict) # 👉️ {'a': 1, 'c': 3} -
You can also convert the keys of the dictionary to a list and iterate over the list of keys.
my_dict = {'a': 1, 'b': 2, 'c': 3} for key in list(my_dict.keys()): print(key) if key == 'b': del my_dict[key] print(my_dict) # 👉️ {'a': 1, 'c': 3}
answered Dec 6, 2022 at 22:11
If the values in the dictionary were unique too, then I used this solution:
keyToBeDeleted = None
for k, v in mydict.items():
if(v == match):
keyToBeDeleted = k
break
mydict.pop(keyToBeDeleted, None)
answered Nov 23, 2022 at 13:39
Ganesh SGanesh S
3736 silver badges23 bronze badges
- Creating a Shallow Copy of the Dictionary
- Casting Dictionary Items to a List
- Appending Keys to an Empty List

This Runtime error occurs when we remove, modify, or add new entries in a dictionary object during iteration. This error occurs when iterating through a dictionary but virtually all iterable objects regardless of the programming language used.
The code snippet below illustrates how this error comes about when iterating through a dictionary and making changes simultaneously.
cars = {
"brand": "Tesla",
"model": "Model S Plaid",
"year": 2021
}
for x in cars.keys():
cars["color"] = "white"
print(x)
In the code block above, we add a new item to the original dictionary while iterating. This will return a Runtime Error, letting us know that the dictionary size changed during iteration, implying that we cannot modify the dictionary while iterating simultaneously.
Sample Code:
Traceback (most recent call last):
File "<string>", line 8, in <module>
RuntimeError: dictionary changed size during iteration
While performing any iteration to an object, both deletion, addition, or modification are considered an alteration and cannot be performed while iterating. The code example below demonstrates that this error will also persist if we modify the dictionary while iterating. Therefore, we will still get the same error if we remove an existing item from a dictionary while iterating.
Sample Code:
cars = {
"brand": "Tesla",
"model": "Model S Plaid",
"year": 2021
}
for x in cars.keys():
del cars["model"]
print(cars)
Output:
Traceback (most recent call last):
File "<string>", line 8, in <module>
RuntimeError: dictionary changed size during iteration
In Python 3, iterating over a changing object is considered a bad style of writing code and unsafe. Generally, in Programming, we cannot mutate an object while iterating over it simultaneously; this rule extends to iterables such as lists and even arrays.
However, if a function mutates an object, we must make sure that the function only mutates a copy of the original object, leaving the original object intact. This is one of the widely used approaches of making alterations to objects while iterating through them simultaneously.
This is a good practice and the best way of avoiding instances of creating an infinite loop that may eventually lead to memory exhaustion. Several solutions can be used to handle this error, and we will discuss each one here.
Creating a Shallow Copy of the Dictionary
Python provides us with the copy() module that allows us to create a copy of an object with no binding to the original object. This lets us freely modify the copy of the object, leaving the original object intact.
Note that the same cannot be realized by using the assignment operator in Python. Using the assignment operator does not create a copy of the original object but rather a variable that refers to the original object.
Therefore any modifications made to the new object will also affect the original object. New developers often misuse this operator.
Sample Code:
import copy
cars = {
"brand": "Tesla",
"model": "Model S Plaid",
"year": 2021,
}
#creating a shallow copy
cars_copy = copy.copy(cars)
for x in cars_copy.keys():
cars["color"] = "black"
print(cars)
print(cars_copy)
Output:
{'brand': 'Tesla', 'model': 'Model S Plaid', 'year': 2021, 'color': 'black'}
{'brand': 'Tesla', 'model': 'Model S Plaid', 'year': 2021}
In the sample code provided, we have used the copy module’s copy function to create a dictionary copy that we can freely iterate without affecting the original dictionary. Making changes to a dictionary copy allows us to iterate over the dictionary without encountering an error.
Alternatively, we can use the ** operator that is often referred to as the two asterisk operators to rewrite the code above, as shown below.
Sample Code:
cars = {
"brand": "Tesla",
"model": "Model S Plaid",
"year": 2021
}
#creating a shallow copy
cars_copy = {**cars}
for x in cars_copy.keys():
cars["color"] = "black"
print(cars)
The ** operator can take key-value pairs from one dictionary and dump them into another dictionary.
Although the operator is widely used to pass in keyword arguments in Python, we have used the operator to unpack the dictionary and obtain the key-value pairs in the code above. We then create a copy of the dictionary and dump the unpacked values in this new dictionary.
Output:
'brand': 'Tesla', 'model': 'Model S Plaid', 'year': 2021, 'color': 'black'}
Deleting a key-value pair from a dictionary is no exception either when performing an iteration and thus should follow a similar approach. Therefore using the same procedure, we will delete the key named model and its value Model S Plaid as shown below.
Sample Code:
import copy
cars = {
"brand": "Tesla",
"model": "Model S Plaid",
"year": 2021,
"color": "black"
}
cars_copy = copy.copy(cars)
for x in cars_copy.keys():
if x == "model":
del cars["model"]
print(cars)
Output:
{'brand': 'Tesla', 'year': 2021, 'color': 'black'}
Another solution would be to create a copy of the keys that we can then iterate over while modifying the dictionary. However, this can only work in Python 2 and not Python 3 because when done in Python 3, the keys do not return the iterable.
Sample Code:
cars = {
"brand": "Tesla",
"model": "Model S Plaid",
"year": 2021,
"color": "black"
}
key_copys = list(cars.keys())
print(key_copys)
for key in list(key_copys):
if cars[key] == "model":
cars.pop("model")
print(cars)
Sample Output:
['brand', 'model', 'year', 'color']
{'brand': 'Tesla', 'model': 'Model S Plaid', 'year': 2021, 'color': 'black'}
Casting Dictionary Items to a List
Since we cannot iterate over the dictionary while making changes, we can instead create a casting list and iterate over the list while making changes to the dictionary. Iterating over the casting list instead of the original dictionary does not return a Runtime error.
Sample Code:
cars = {
"brand": "Tesla",
"model": "Model S Plaid",
"year": 2021
}
for i in list(cars):
cars["color"] = "black"
print(cars)
Output:
{'brand': 'Tesla', 'model': 'Model S Plaid', 'year': 2021, 'color': 'black'}
Appending Keys to an Empty List
To avoid changing the dictionary while iterating, we can create an empty list containing the dictionary keys while we perform the iteration. Using this empty list, we can append all the keys that we want to remove or change and then use the pop() function to remove the keys or the append function to add new key-value pairs.
This can be executed as shown in the code below.
Sample Code:
cars = {
"brand": "Tesla",
"model": "Model S Plaid",
"year": 2021
}
list = []
for i in cars:
list.append(i)
for x in list:
if x == "model":
cars.pop(x)
print(cars)
Output:
{'brand': 'Tesla', 'year': 2021}
As shown below, we can add a new key-value pair to the dictionary using the same procedure while iterating using the for loop.
Sample Code:
cars = {
"brand": "Tesla",
"model": "Model S Plaid",
"year": 2021
}
list = []
for i in cars:
list.append(i)
for x in list:
cars["color"] = "black"
print(cars)
Output:
{'brand': 'Tesla', 'model': 'Model S Plaid', 'year': 2021, 'color': 'black'}
In this article, we will discuss what causes the “RuntimeError: dictionary changed size during iteration” error. In addition, you will know how to use copy(), keys() and some other methods to deal with this error, follow the details below.
In Python, RuntimeError is classed as exception error types. Errors usually occur when there is a problem with the logic of the program. Usually it’s pretty hard to spot while you’re coding. Suppose in this situation, when you enter the following program, the error “RuntimeError: dictionary changed size during iteration” occurred:
Error code
student = {
"firstName": "Liza",
"lastName": "Nguyen",
"yearofBirth": 2000
}
for s in student.keys():
student["department"] = "IT"
print("student:", student)
Output:
---------------------------------------------------------------------------
RuntimeError Traceback (most recent call last)
<ipython-input-61-6bbcf4bfc185> in <module>
5 }
6
----> 7 for s in student.keys():
8 student["department"] ="IT"
9
RuntimeError: dictionary changed size during iteration
What causes error?
The error “RuntimeError: dictionary changed size during iteration” informs the coder that: During the execution of the loop instruction, the size of the visible word has been changed. That is, you cannot make modifications while iterating, which will cause a runtime error.
How to fix it?
To help you quickly and effectively solve the above error, we have summarized some methods below. Let’s take a look and choose the method that is suitable for you.
Solution 1: Using copy() function
The purpose of this method is that you can use the copy() function that Python provides to create a new copy that is not affected by the original. From there you can easily edit the copy while keeping the original.
For example:
import copy
student = {
"firstName": "Liza",
"lastName": "Nguyen",
"yearofBirth": 2000
}
copyStudent = copy.copy(student)
for s in copyStudent.keys():
student["department"] = "IT"
print("student:", student)
print("copyStudent:", copyStudent)
Output:
student: {'firstName': 'Liza', 'lastName': 'Nguyen', 'yearofBirth': 2000, 'department': 'IT'}
copyStudent: {'firstName': 'Liza', 'lastName': 'Nguyen', 'yearofBirth': 2000}
Solution 2: Using keys() function
With this method, we will create a list of keywords in the dictionary and after returning the result will be a new unaffected list.
For instance:
student = {
"firstName": "Liza",
"lastName": "Nguyen",
"yearofBirth": 2000
}
keyStudent = list(student.keys())
print("keyStudent", keyStudent)
for key in keyStudent:
if key == "yearofBirth":
student[key] = 2001
print("student", student)
Output:
keyStudent ['firstName', 'lastName', 'yearofBirth']
student {'firstName': 'Liza', 'lastName': 'Nguyen', 'yearofBirth': 2001}
Solution 3: Use the ** operator
This method will take the key-value pairs from one dictionary and pass it to another dictionary. This is also another way to get a copy of a dictionary or list.
Code sample:
student = {
"firstName": "Liza",
"lastName": "Nguyen",
"yearofBirth": 2000
}
copyStudent = {**student}
for s in copyStudent.keys():
student["department"] = "IT"
print("student:", student)
print("copyStudent:", copyStudent)
Output
student: {'firstName': 'Liza', 'lastName': 'Nguyen', 'yearofBirth': 2000, 'department': 'IT'}
copyStudent: {'firstName': 'Liza', 'lastName': 'Nguyen', 'yearofBirth': 2000}
Solution 4: Pass the new dictionary object to the list
With this method, by creating a cast list and manipulating changes through it, the iteration won’t cause the above error.
For example:
student = {
"firstName": "Liza",
"lastName": "Nguyen",
"yearofBirth": 2000
}
for lst in list(student):
student["department"] = "IT"
print("student:", student)
Output
student: {'firstName': 'Liza', 'lastName': 'Nguyen', 'yearofBirth': 2000, 'department': 'IT'}
Conclusion
This is how you are able to solve this type of task “RuntimeError: dictionary changed size during iteration”. However, we have provided relevant expertise to develop a more research-oriented mindset, and make it easier for you to answer these type questions. Please leave a message below if you have any questions or comments. Thanks for reading!
Maybe you are interested:
- Series Objects Are Mutable and Cannot be Hashed

What Causes This Runtimeerror in Python?
Usually, Python will slap you with this error when you try to modify entries in a dictionary object during iteration. It occurs whenever iterating through a dictionary and virtually all iterable objects. To understand this error, below are some code snippets that illustrate that show the cause of this error by iterating through a dictionary and performing changes simultaneously.
– Example 1: Adding a New Dictionary Item While Iterating
Suppose you have a dictionary that holds the brand, model, and year of a vehicle. If you try to add a new item, say the color of the car during iteration, Python will throw this runtime error. Here is an example that generates this error:
vehicle = {
“Brand”: “Honda”,
“Model”: “Civic Type R”,
“Year”: 2022
}
print(vehicle)
for c in vehicle.keys():
vehicle[“color”] = “Blue”
print(c)
The above code tries to add color to the original dictionary during iteration, which returns the runtimeerror.
In this error, Python is letting you know that the size of the python dictionary was updated during iteration. It indicates that you cannot change the dictionary while simultaneously iterating. Keep in mind that during an iteration trying to delete, modify, or add an item to a python dictionary will not happen. Instead, Python will throw you this error.
– Example 2: Removing an Item From a Dictionary During Iteration
Suppose you now wish to delete an item like the year in the previous vehicle dictionary example. Attempting to delete the year while iterating will yield the same runtime error.
Here is the Python code that will generate the same error:
vehicle = {
“Brand”: “Honda”,
“Model”: “Civic Type R”,
“Year”: 2022
}
print(vehicle)
for c in vehicle.keys():
del vehicle[“Model”]
print(c)
When writing a program in Python, remember iterating a changing object is an unsafe and wrong style of coding. It is not just in Python, generally in programming, mutating an object while performing iterations on it is something you cannot do. The rule applies to other iterables like arrays and lists.
How To Solve This Runtime Error
With Python, you can solve this error in various ways. But first, you need to remember that if a function modifies an object, you must ensure the function only modifies a copy of the original. This way, you leave the original dictionary object untouched. This is one of the most common ways of altering objects when performing iterations simultaneously.
Creating a copy is a great way of getting rid of instances that create an infinite loop that can eventually result in memory exhaustion.
– Solution 1: Adding an Item to a Dictionary
Python provides the copy() module that you can use to generate a copy of an object without interfering with the original object. As such, you have the freedom to modify the copy as you wish. One thing you should note is that you will realize this using the assignment operator.
If you use the assignment operator, you will be creating a variable that uses the original object as the reference point instead of creating a copy of the original object. Therefore, any changes that take place in the new object will reflect in the original object. However, note that often, new developers tend to misuse this operator.
– Example 1: Using a Copy of the Original Dictionary
Suppose you wish to include color in the vehicle dictionary you created earlier. You can accomplish this like so:
import copy
vehicle = {
“Brand”: “Honda”,
“Model”: “Civic Type R”,
“Year”: 2022
}
#creating a shallow copy of the original object
vehicle_copy = copy.copy(vehicle)
for c in vehicle_copy.keys():
vehicle[“Color”] = “Blue”
print(“The output for the vehicle will be: “, vehicle)
print(“The output for the vehicle copy will be: “, vehicle_copy)
Running the above code will generate the following output:
The output for the vehicle copy will be: {‘Brand’: ‘Honda’, ‘Model’: ‘Civic Type R’, ‘Year’: 2022}
Notice how you use the copy module to generate a copy of the original dictionary. Now using the copy, you had the freedom to iterate without interfering with the original dictionary. Modifying the copy allows you to iterate the original dictionary without generating the runtime error.
– Example 2: Using ** Operator
Alternatively, you can use the two asterisk operator to create a copy of the original dictionary like so:
import copy
vehicle = {
“Brand”: “Honda”,
“Model”: “Civic Type R”,
“Year”: 2022
}
#creating a copy of the original object
vehicle_copy = {**vehicle}
for c in vehicle_copy.keys():
vehicle[“Color”] = “Blue”
print(“The output for the vehicle will be: “, vehicle)
print(“The output for the vehicle copy will be: “, vehicle_copy)
Using the ** operator, Python lets you copy key-value pairs in one dictionary and then dump them into a different dictionary. Often, this Python operator is useful for passing keyword arguments. But, in this case, you use it to let Python copy the dictionary by unpacking the original dictionary and obtaining the key-value pairs within it. The operator then dumbs the unpacked values in the new dictionary.
If you run the code above, you will get the following output:
The output for the vehicle copy will be: {‘Brand’: ‘Honda’, ‘Model’: ‘Civic Type R’, ‘Year’: 2022}
– Solution 2: Deleting an Item in the Dictionary
When removing a key-value pair in a dictionary, you still have to follow the same rules when performing iterations.
– Example 1: Using a Copy of the Original Dictionary
Suppose you want to let Python modify the dictionary while iterating, using the vehicle example, you may decide to delete the key named year together with its value (2022). You can accomplish this like so:
import copy
vehicle = {
“Brand”: “Honda”,
“Model”: “Civic Type R”,
“Year”: 2022
}
#creating a copy of the original object
vehicle_copy = copy.copy(vehicle)
for c in vehicle_copy.keys():
if c == “Year”:
del vehicle[“Year”]
print(“The output for the vehicle will be: “, vehicle)
print(“The output for the vehicle copy will be: “, vehicle_copy)
The output will be:
The output for the vehicle copy will be: {‘Brand’: ‘Honda’, ‘Model’: ‘Civic Type R’, ‘Year’: 2022}
– Example 2: Using a Copy of the Keys
Another way you can delete the content of a dictionary is by creating a copy of the keys. you can then use the copy to iterate and modify the dictionary. This is another practical way of solving this error in Python.
vehicle = {
“Brand”: “Honda”,
“Model”: “Civic Type R”,
“Year”: 2022
}
#creating a copy of the original object
vehicle_copy = list(vehicle.keys())
print(“The output for the vehicle copy will be: “, vehicle_copy)
for c in list(vehicle_copy):
if vehicle[c] == “Year”:
vehicle.pop[“Year”]
print(“The output for the vehicle will be: “, vehicle)
The output is as follows:
The output for the vehicle will be: {‘Brand’: ‘Honda’, ‘Model’: ‘Civic Type R’, ‘Year’: 2022}
– Solution 3: Casting Dictionary Objects to a List
Because you cannot iterate a dictionary and make changes simultaneously, you need to come up with a casting list that lets you iterate to modify a dictionary. This approach does not generate the runtime error.
– Example: Add an Item to a Dictionary
Suppose you decide to add color to the original vehicle dictionary, you can accomplish this by casting the dictionary to a list like so:
vehicle = {
“Brand”: “Honda”,
“Model”: “Civic Type R”,
“Year”: 2022
}
for c in list(vehicle):
vehicle[“Color”] = “Blue”
print(“The output for the vehicle will be: “, vehicle)
This will result in:
The output for the vehicle will be: {‘Brand’: ‘Honda’, ‘Model’: ‘Civic Type R’, ‘Year’: 2022, ‘Color’: ‘Blue’}
– Solution 4: Using an Empty List With Dictionary Keys
Another way of ensuring you do not modify the dictionary during iteration entails creating an empty list with dictionary keys to perform iterations on. You can then use the empty list to append all the keys you wish to modify. If you wish to delete an item, use the pop() function. Alternatively, you can use the append() function to add new items to a dictionary.
– Example 1: Removing an Item From a Dictionary
Say you want to let python delete the dictionary key while iterating. Here is an example of how you can use an empty list to delete items in a dictionary. Using the vehicle dictionary example, suppose you decide to delete the year. You can accomplish this like so:
vehicle = {
“Brand”: “Honda”,
“Model”: “Civic Type R”,
“Year”: 2022
}
list = []
for c in vehicle:
list.append(c)
for d in list:
if d == “Year”:
vehicle.pop(d)
print(“The output for the vehicle will be: “, vehicle)
The code above will generate the following output:
The output for the vehicle will be: {‘Brand’: ‘Honda’, ‘Model’: ‘Civic Type R’}
– Example 2: Adding New Items Using an Empty List
Suppose you want to add color to the vehicle dictionary you created earlier. Here is how you can accomplish this using an empty list without concerns of triggering the python list changed size during iteration warning:
vehicle = {
“Brand”: “Honda”,
“Model”: “Civic Type R”,
“Year”: 2022
}
list = []
for c in vehicle:
list.append(c)
for d in list:
vehicle[“Color”] = “Blue”
print(“The output for the vehicle will be: “, vehicle)
Running the above code will generate the following output:
The output for the vehicle will be: {‘Brand’: ‘Honda’, ‘Model’: ‘Civic Type R’, ‘Year’: 2022, ‘Color’: ‘Blue’}
Conclusion
If you get this error when programming in Python, there are a few things you should keep in mind:
- Check if you are trying to simultaneously modify a dictionary during iteration.
- In addition, you will get this error when trying to perform the same operations on arrays and lists
- To solve this error, you need to create a copy of the original dictionary
- Python lets you solve it using the ** operator, empty list, and casting list
- You can then modify the copy and the original dictionary without issues

- Author
- Recent Posts
Position Is Everything: Your Go-To Resource for Learn & Build: CSS,JavaScript,HTML,PHP,C++ and MYSQL.
In this article, we will discuss different ways to delete key-value pairs from a dictionary while iterating over it.
Table of Contents
- Problem in deleting items from dictionary while iterating
- [Solved] – Remove key-value pairs from dictionary during Iteration
- Delete items from dictionary while iterating using comprehension
- Iterate over a dictionary and remove items using pop() function
Can you actually change the size of dictionary during iteration in Python?
Issue in deleting items from dictionary while iterating [Problem]
Dictionary changed size during iteration in python
If you are planning to iterate over dictionary using a for loop and want to delete elements while iteration. Then you can not just call the dictionary’s pop() function or del keyword during the for loop because dictionary size can not change while iteration and if you will try to do that then it will give error. Checkout this example,
# Dictionary of string and integers
word_freq = {
'Hello' : 56,
'at' : 23,
'test' : 43,
'This' : 78,
'Why' : 11
}
# Wrong way to delete an item from dictionary while iteration
# RuntimeError: dictionary changed size during iteration
for key, value in word_freq.items():
if value == 23:
del word_freq[key]
print(word_freq)
This code will following error,
Advertisements
Traceback (most recent call last):
File ".iterate_delete.py", line 16, in <module>
for key, value in word_freq.items():
RuntimeError: dictionary changed size during iteration
It gave the RuntimeError, because we can not change the size of dictionary while iteration. So, to delete key-value pairs from dictionary we need to create a copy of dictionary first. Let’s see how to do that,
Remove key-value pairs from dictionary during Iteration [Solved]
We can create a copy of dictionary and iterate over that and delete elements from original dictionary while iteration. For example, we have a dictionary of string and integers. We want to delete all iterate over this dictionary and delete items where value is matching a given value. Let’s see how to do that,
# Dictionary of string and integers
word_freq = {
'Hello' : 56,
'at' : 23,
'test' : 43,
'This' : 78,
'Why' : 11
}
# Delete an item from dictionary while iteration
for key, value in dict(word_freq).items():
if value == 23:
del word_freq[key]
print(word_freq)
Output:
{'Hello': 56,
'test': 43,
'This': 78,
'Why': 11}
We created a copy of original dictionary word_freq and iterated over all key-value pairs of this dictionary copy. Then during iteration, for each key-value pair we checked if value is 23 or not. if yes, then we deleted the pair from original dictionary word_freq. It gave an effect that we have deleted elements from dictionary during iteration.
Let’s checkout another example,
Iterate over a dictionary and remove items with even values
# Dictionary of string and integers
word_freq = {
'Hello' : 56,
'at' : 23,
'test' : 43,
'This' : 78,
'Why' : 11
}
# Delete items from dictionary while iterating
# and based on conditions on values
for key, value in dict(word_freq).items():
if value % 2 == 0:
del word_freq[key]
print(word_freq)
Output:
{'at': 23,
'test': 43,
'Why': 11}
Delete items from dictionary while iterating using comprehension
We can use dictionary comprehension to filter items from a dictionary based on condition and assign back the new dictionary to original reference variable. For example,
Iterate over a dictionary and remove items with even values
# Dictionary of string and integers
word_freq = {
'Hello' : 56,
'at' : 23,
'test' : 43,
'This' : 78,
'Why' : 11
}
# Delete items from dictionary while iterating using comprehension
# and based on conditions on values
word_freq = { key: value
for key, value in word_freq.items()
if value % 2 != 0}
print(word_freq)
Output:
{'at': 23,
'test': 43,
'Why': 11}
Here we iterated over all key-value pairs of dictionary and created a new dictionary with only those items where value is not even. Then we assigned this new dictionary to original reference variable. It gave an effect that we have deleted items from dictionary where value is even.
Iterate over a dictionary and remove items using pop() function
Just like the first solution, we can create a copy of original dictionary and iterate over it. During iteration we can apply a condition on each pair and if condition is satisfied then we can delete that element from original dictionary. But here we will use pop() function instead of del keyword to delete elements during iteration. For example,
# Dictionary of string and integers
word_freq = {
'Hello' : 56,
'at' : 23,
'test' : 43,
'This' : 78,
'Why' : 11
}
for key in dict(word_freq):
if word_freq[key] % 2 == 0:
word_freq.pop(key)
print(word_freq)
Output:
{'at': 23,
'test': 43,
'Why': 11}
Here we iterated over all key-value pairs of dictionary and during iteration deleted items where value is even.
Pro Tip:
pop() function accepts a key and a default value as arguments. If key is present in the dictionary, then it deletes that. Also, it returns,
- The value of deleted item if key exist in dictionary.
- The default value if key doesn’t exist in the dictionary.
- KeyError if key does not exist in the dictionary and default value is also not provided.
Summary:
We learned different ways to delete key-value pairs from dictionary during iteration.
Advertisements
Thanks for reading.
