I am writing a program in which I need to iterate through many long dictionaries, so I thought I could remove unneeded values from it, to save on some runtime. Here is a minimal working example with lacking context:
years = {0: 2019, 1: 2020, 2: 2021}
def iterate_years():
for i in years:
temp_years = years
print("years:", years)
print("temp_years:", temp_years)
temp_years.pop(i)
minimum = min(temp_years)
maximum = max(temp_years)
print("temp_years:", years)
print("years:", years)
iterate_years()
When I run this it returns a runtime error because the size f the dictionary changed while iteration. As you can see through the example the line temp_years.pop(i)
seems to pop the key-value pair i
in temp_years, as specified but also in years
.
Why does this happen? I am not very experienced but years
is never assigned to temp_years
after the pop()
so the value for years
should stay like they were specified in the first line.