How to delete a value from a dictionary during a for loop
📁 Advanced Python Topics, Error, example
Somehow unexpectedly encountered this problem. During a for loop over a dictionary, I need to delete entries from it, but no matter what I do, I get an error:
RuntimeError: dictionary changed size during iterationI even tried taking a snapshot of the dictionary before iteration and iterating over the copy while deleting from the original.
Example:
>>> ot={12:'wqe',13:'wqe',14:'wqe',15:'wqe'}>>> ot1=ot>>>
This is a bug in Python 3.4+: .
As a workaround,
Log in to leave an answer
Blogs
Top 10 JavaScript Frameworks for Web Development in 2025
Monorepo with Kotlin: Practical Code Organization
Feature flags in C++: managing features without pain and rebuilding
C++ at the Limit: Profiling and Code Optimization for Maximum Speed