Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I remove keys with values of 0, while scanning the dictionary to search for keys with values of 0?

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!

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading