Deleting while iterating
Just found out that you can’t del
keys from a dict while iterating through it.
Say, we have the following dictionary:
1{
2 "Alabama": {
3 "USState": "Alabama",
4 "Persons": 2,
5 },
6 "Missouri": {
7 "USState": "Missouri",
8 "Persons": 0,
9 },
10 "Idaho": {
11 "USState": "Idaho",
12 "Persons": 0,
13 }
14}
This doesn’t work:
1for s in states.keys():
2 if states[s]["Persons"] == 0:
3 del states[s]
as it will through a RuntimeError: dictionary changed size during iteration
at us!
(OK, it will actually delete the first found case and right afterwards through the error at us)
To delete while iterating over a dictionary, you have to iterate over a copy of the dictionary and delete from base dictionary:
1for s in states.copy().keys():
2 if states[s]["Persons"] == 0:
3 del states[s]