For Python 3+:

>>> mydict
{'four': 4, 'three': 3, 'one': 1}

>>> for k in list(mydict.keys()):
...     if mydict[k] == 3:
...         del mydict[k]

>>> mydict
{'four': 4, 'one': 1}

The other answers work fine with Python 2 but raise a RuntimeError for Python 3:

RuntimeError: dictionary changed size during iteration.

This happens because mydict.keys() returns an iterator not a list. As pointed out in comments simply convert mydict.keys() to a list by list(mydict.keys()) and it should work.


For Python 2:

A simple test in the console shows you cannot modify a dictionary while iterating over it:

>>> mydict = {'one': 1, 'two': 2, 'three': 3, 'four': 4}

>>> for k, v in mydict.iteritems():
...    if k == 'two':
...        del mydict[k]

------------------------------------------------------------
Traceback (most recent call last):
  File "<ipython console>", line 1, in <module>
RuntimeError: dictionary changed size during iteration

As stated in delnan's answer, deleting entries causes problems when the iterator tries to move onto the next entry. Instead, use the keys() method to get a list of the keys and work with that:

>>> for k in mydict.keys():
...    if k == 'two':
...        del mydict[k]

>>> mydict
{'four': 4, 'three': 3, 'one': 1}

If you need to delete based on the items value, use the items() method instead:

>>> for k, v in mydict.items():
...     if v == 3:
...         del mydict[k]

>>> mydict
{'four': 4, 'one': 1}
Answer from Blair on Stack Overflow
Top answer
1 of 13
469

For Python 3+:

>>> mydict
{'four': 4, 'three': 3, 'one': 1}

>>> for k in list(mydict.keys()):
...     if mydict[k] == 3:
...         del mydict[k]

>>> mydict
{'four': 4, 'one': 1}

The other answers work fine with Python 2 but raise a RuntimeError for Python 3:

RuntimeError: dictionary changed size during iteration.

This happens because mydict.keys() returns an iterator not a list. As pointed out in comments simply convert mydict.keys() to a list by list(mydict.keys()) and it should work.


For Python 2:

A simple test in the console shows you cannot modify a dictionary while iterating over it:

>>> mydict = {'one': 1, 'two': 2, 'three': 3, 'four': 4}

>>> for k, v in mydict.iteritems():
...    if k == 'two':
...        del mydict[k]

------------------------------------------------------------
Traceback (most recent call last):
  File "<ipython console>", line 1, in <module>
RuntimeError: dictionary changed size during iteration

As stated in delnan's answer, deleting entries causes problems when the iterator tries to move onto the next entry. Instead, use the keys() method to get a list of the keys and work with that:

>>> for k in mydict.keys():
...    if k == 'two':
...        del mydict[k]

>>> mydict
{'four': 4, 'three': 3, 'one': 1}

If you need to delete based on the items value, use the items() method instead:

>>> for k, v in mydict.items():
...     if v == 3:
...         del mydict[k]

>>> mydict
{'four': 4, 'one': 1}
2 of 13
121

You could also do it in two steps:

remove = [k for k in mydict if k == val]
for k in remove: del mydict[k]

My favorite approach is usually to just make a new dict:

# Python 2.7 and 3.x
mydict = { k:v for k,v in mydict.items() if k!=val }
# before Python 2.7
mydict = dict((k,v) for k,v in mydict.iteritems() if k!=val)
🌐
freeCodeCamp
freecodecamp.org › news › how-to-remove-a-key-from-the-dictionary-while-iterating-over-it-definitive-guide
How to Remove a Key from a Dictionary While Iterating Over it
July 6, 2022 - Now during each iteration, you can check if the item is equal to the key you want to delete. And if it is equal, you can issue the del statement. It’ll remove the key from the dictionary.
Discussions

Managing adding/removing items from a dictionary while iterating over it periodically
You can make a list of the keys before iterating, and use that instead of the dictionary's built-in iterator: >>> d = {"a":1, "b":2} >>> for key in d: ... del d[key] ... Traceback (most recent call last): File "", line 1, in RuntimeError: dictionary changed size during iteration >>> d = {"a":1, "b":2} >>> keys = list(d.keys()) >>> for key in keys: ... del d[key] >>> d {} No errors! More on reddit.com
🌐 r/learnpython
8
2
September 24, 2018
python - Remove element from dictionary by key while iterating - Stack Overflow
In order to filter list of dictionaries from empty values I need to remove ~30% of data from dictionaries. So I've end up with this code: qr = query_result for row in qr: for key, v... More on stackoverflow.com
🌐 stackoverflow.com
May 19, 2017
python - Deleting items from a dictionary with a for loop - Stack Overflow
Due to the fact that Python dictionaries are implemented as hash tables, you shouldn't rely on them having any sort of an order. Key order may change unpredictably (but only after insertion or removal of a key). Thus, it's impossible to predict the next key. Python throws the RuntimeError to be safe, and to prevent people from running into unexpected results. Python 2's dict.items method returns a copy of key-value pairs, so you can safely iterate ... More on stackoverflow.com
🌐 stackoverflow.com
May 11, 2014
python - Unable to delete a dictionary key while iterating over it in python3: "RuntimeError: dictionary changed size during iteration" - Stack Overflow
Is python not allow to remove any dictionary key while iterating through a dictionary? 2018-03-23T07:55:58.88Z+00:00 ... new_dict = mydict does not work the way you think it does. Python has a different mechanism. You need to read about copying objects in python. 2018-03-23T07:58:56.72Z+00:00 ... Do not try to delete it while iterating the dictionary. Do not copy the dictionary, iterate and delete. Do not create a list of tuples from ... More on stackoverflow.com
🌐 stackoverflow.com
March 23, 2018
🌐
GeeksforGeeks
geeksforgeeks.org › python › remove-a-key-from-a-python-dictionary-using-loop
Remove a Key from a Python Dictionary Using loop - GeeksforGeeks
July 23, 2025 - For example, consider the dictionary d = {'a': 1, 'b': 2, 'c': 3}. If we want to remove the key 'b', we need to handle this efficiently, especially to avoid issues like modifying the dictionary during iteration. Let's explore different methods to remove a key from a dictionary using a loop. A dictionary comprehension allows us to construct a new dictionary without the unwanted key in a single step. ... d = {'a': 1, 'b': 2, 'c': 3} # Key to remove key = 'b' # Recreate dictionary without the unwanted key d = {k: v for k, v in d.items() if k != key} print(d)
🌐
thisPointer
thispointer.com › home › dictionary › python: iterate over dictionary and remove items
Python: Iterate over dictionary and remove items - thisPointer
February 19, 2021 - 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. ... # 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)
🌐
Quora
quora.com › Working-in-Python-how-can-I-delete-items-while-iterating-over-a-dictionary
Working in Python, how can I delete items while iterating over a dictionary? - Quora
Answer (1 of 6): I’m not so concerned about modifying a container while iterating over it, as long as you understand what you’re doing. And the nice thing is that this presents an opportunity to talk about how dictionary methods have changed between Python 2 and Python 3. In Python 2, the ...
🌐
Scaler
scaler.com › home › topics › remove key from dictionary python
remove key from dictionary python | Scaler Topics
May 4, 2023 - Explanation: Calling the pop() method on the dictionary dict iteratively removes all the keys that were present in the list keys_to_remove. Both pop() method and del keyword can be used to remove key from dictionary in Python (as we saw above).
🌐
TutorialsPoint
tutorialspoint.com › article › delete-items-from-dictionary-while-iterating-in-python
Delete items from dictionary while iterating in Python
This prevents modification of the dictionary during iteration ? # Given dictionary days_dict = {1: 'Mon', 2: 'Tue', 3: 'Wed', 4: 'Thu', 5: 'Fri'} # Get keys with value in 2,3 to_del = [key for key in days_dict if key in (2, 3)] # Delete keys for key in to_del: del days_dict[key] # New Dictionary print(days_dict)
Find elsewhere
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-delete-items-from-dictionary-while-iterating
Python | Delete items from dictionary while iterating - GeeksforGeeks
July 11, 2025 - 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.
🌐
thisPointer
thispointer.com › home › dictionary › python : how to remove multiple keys from dictionary while iterating ?
Python : How to Remove multiple keys from Dictionary while Iterating ? - thisPointer
October 19, 2019 - 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]
🌐
Expertbeacon
expertbeacon.com › home › expert guide: how to safely remove dictionary keys while iterating in python
Expert Guide: How To Safely Remove Dictionary Keys While Iterating In Python - ExpertBeacon
August 26, 2024 - In Python 2, wrapping is recommended for portability and future-proofing. Prefer sets where order doesn‘t matter. Set iterations are safe for removals in all versions. Make small functional updates – Rather than deleting in a loop, rebuild the dictionary. Use masking techniques if retaining invalid keys is beneficial. These tips will help avoid unexpected bugs when you need to remove keys while iterating.
🌐
Reddit
reddit.com › r/learnpython › managing adding/removing items from a dictionary while iterating over it periodically
r/learnpython on Reddit: Managing adding/removing items from a dictionary while iterating over it periodically
September 24, 2018 -

Hello Redditors,

I've basically the following question. In another thread I got help with a code, a "timers table" all is working fine, now I have a question related on how to manage the writing/erasing of items on this table (which is actually a dictionary) when it's being iterated over. I did some tests and found out you can't add or remove items to the dictionary while it's being iterated, it'll raise a runtime error.

So right now I'm struggling on how to fix this, some basic ideas I have, and I'd like to know which one you believe is the better one or if there's a built-in function I'm missing.

  • Idea #1: I create a "flag" (boolean true/false). General idea is, if this flag is set as True, no one can write/delete (it signals an iteration is happening), once the flag is set as False, iterations can't happen but the other process is allowed to write/delete - I'd need to have some sort of routine than once a new item is going to be added/removed checks for this flag until it can actually add it to the dictionary.

  • Idea #2: I make some sort of queue, a deletion queue and a addition queue, once iteration is over, I go through the deletion queue and then the addition queue (adding, deleting items), then iteration happens again. But then I think I'll get into the same problem as with the dictionary.

  • Idea #3: Make a copy of the dictionary and iterate over this copy instead of the main one, allowing to always have the main one accessible for write/read. I don't expect the dictionary to have a lot of items, ideally would not have more than 3 - 10 items on any given time.

The code is quite simple, basically all I need to do is to push items to this dict, track time and do something once the time is up. In any given time I should be able to add/remove items to this dictionary.

🌐
Bomberbot
bomberbot.com › python › how-to-remove-a-key-from-a-python-dictionary-delete-keys-from-dicts
How to Remove a Key from a Python Dictionary – Delete Keys from Dicts - Bomberbot
There are a few potential issues to watch out for when removing dictionary keys: Deleting keys during iteration: Modifying a dictionary while iterating over it can lead to unexpected behavior or RuntimeErrors. If you need to delete keys during iteration, iterate over a copy of the keys instead ...
🌐
CodeRivers
coderivers.org › blog › remove-key-from-dictionary-python
Removing Keys from a Dictionary in Python - CodeRivers
February 22, 2026 - In this code, first, a list of keys to remove is created using a list comprehension. Then, each key in that list is removed from the dictionary using the del statement. Iterating over a dictionary while directly removing keys can be tricky because modifying the dictionary size during iteration can lead to unexpected results.
🌐
Real Python
realpython.com › lessons › modify-values-dictionary-while-iterating-through-it
How to Modify Values in a Dictionary While Iterating Through It (Video) – Real Python
But there are some circumstances ... And I failed to mention that the way to remove a key is you use this this Python inbuilt del (delete) keyword....
Published   December 24, 2019
🌐
Edureka Community
edureka.co › home › community › categories › python › how to delete items from a dictionary while...
How to delete items from a dictionary while iterating over it | Edureka Community
April 30, 2020 - Is it legitimate to delete items from a dictionary in Python while iterating over it? For ... good solution? Are there more elegant/efficient ways?
🌐
Solved
code.i-harness.com › en › q › 522ad2
scripting - while - remove multiple keys from dictionary python - Solved
Basically you make a copy of your dict() and iterate over that while deleting the entries in your original dictionary. tmpDict = realDict.copy() for key, value in tmpDict.items(): if value: del(realDict[key])