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
>Solution :
Below code gives the output as expected
my_dict = {'a': 4, 'b':3, 'c':2, 'd':0}
del_keys= []
for key, value in my_dict.items():
if value == 0:
del_keys.append(key)
for key in del_keys:
my_dict.pop(key)
print(my_dict)