I have a dictionary of names and numbers; where names are keys and numbers are the values in the dictionary. I am decrementing the numbers of each key, where at some point the numbers will hit 0.
When they hit 0, I would like to remove the corresponding key from the dictionary. In my code, when I try to do this- I get an error, because as I loop through the dictionary searching for keys with 0 as values, and pop() them from the dictionary- I get an error that says the size of dictionary changes during the iteration.
How can I achieve the above without the error? Am I wrong in looping over the dictionary to remove keys with values of 0? - I understand the problem and agree that it is an issue, but can't seem to think of a way to achieve this!
Would I need to initialise an array/set to store the keys with values of 0, then remove them after?- or is there a more efficient way?
pat = dict()
pat['ff']= 5
pat['dd'] = 4
pat['pat'] = 0
for i in pat:
if pat[i] == 0:
pat.pop(i)
Error: RuntimeError: dictionary changed size during iteration