0

while running some scripts on dictionaries i found a problem with the functions using .pop in a loop on a dictionary only works once. an example:

randomDictionary = {
    "PERSON1":{"NAME":"Cheese man","AGE":24},
    "PERSON2":{"NAME":"Pepsi Man","AGE":26},
    "PERSON3":{"NAME":"Something else man","AGE":30},
    "PERSON2":{"NAME":"Pepsi Man","AGE":26},
}
for i in randomDictionary:
    if randomDictionary[i]["NAME"] == "Pepsi Man":
        randomDictionary.pop(i)

and the error is:

Traceback (most recent call last):
  File "f:\stuff\visualbackup\Special projects\testingeverything.py", line 7, in <module>
    for i in randomDictionary:
RuntimeError: dictionary changed size during iteration

How do i fix this?

I tried to pop items from a dictionary in a loop, except that i got an error.

Neoro
  • 7
  • 3

2 Answers2

0

Since you are looping over the items of a dictionary, you can't change its size during the loop.

A solution to your problem would be to store the keys that you want to remove in a list and then remove them from the dictionary in another loop over this list. See below:

randomDictionary = {
    "PERSON1":{"NAME":"Cheese man","AGE":24},
    "PERSON2":{"NAME":"Pepsi Man","AGE":26},
    "PERSON3":{"NAME":"Something else man","AGE":30},
    "PERSON2":{"NAME":"Pepsi Man","AGE":26},
}

to_remove = []
for i in randomDictionary:
    if randomDictionary[i]["NAME"] == "Pepsi Man":
        to_remove.append(i)

for i in to_remove:
    randomDictionary.pop(i)
0

rebuild the dictionary using a comprehensive dict:

randomDictionary = {
    "PERSON1":{"NAME":"Cheese man","AGE":24},
    "PERSON2":{"NAME":"Pepsi Man","AGE":26},
    "PERSON3":{"NAME":"Something else man","AGE":30},
    "PERSON2":{"NAME":"Pepsi Man","AGE":26},
}

randomDictionary={key:val for key, val in randomDictionary.items() if val["NAME"] != "Pepsi Man"}
print(randomDictionary)
tetris programming
  • 809
  • 1
  • 2
  • 13