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

Time:12-22

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

CodePudding user response:

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)

CodePudding user response:

Use list(d.keys()) while iterating

d = {"a":1,"b":2,"c":3}
for i in list(d.keys()): #Use like this
    d[i] -= 1
    if d[i] ==0:
        del d[i]

CodePudding user response:

There are many possibilities, but would like to point python's Counter. Removing zeroed elements is as simple as

my_counter  = Counter() 

And you can substract from values with subtract

  • Related