Home > Software engineering >  How to avoid "RuntimeError: dictionary changed size during iteration" or get result withou
How to avoid "RuntimeError: dictionary changed size during iteration" or get result withou

Time:01-11

I have rating of new flavors:

flavors = {"cinnamon": 4, "pumpkin": 2.5, "apple pie": 3}
print("New flavors:")
print(flavors)

for i in flavors:
  if flavors[i] >= 3:
    flavors[i] = True
  else:
    flavors[i] = False

print("Results:")
print(flavors)

I want get list with winning flavors:

for i in flavors:
  if flavors[i] == False:
    flavors.pop(i)

print("Release:")
print(flavors.keys())

Can I get release list without .pop() or avoid RuntimeError?

CodePudding user response:

You cannot alter the keys of a dict while iterating over it. For you purpose you can use a list comprehension instead to build a list of flavors with ratings greater than or equal to 3:

[flavor for flavor, rating in flavors.items() if rating >= 3]

CodePudding user response:

You can't change the keys of the dictionary while iterating over it.

A simple fix to you code is to use for i in list(flavors): instead of for i in flavors: (in the second loop that you remove things). Basically you create a list(new object) of keys, and instead of dictionary, you iterate through this list. Now it's OK to manipulate the original dict.

Additional Note: In previous versions of Python(like 3.7.4 for instance), It allowed to change the keys as long as the size of the dictionary is not changed. For example while you iterate through the dictionary, you pop something and then before the next iteration, you add another key. In general that was buggy and now in my current interpreter (3.10.6) it doesn't allow you to change keys.

  • Related