Home > Blockchain >  How to pop from a dict while looping?
How to pop from a dict while looping?

Time:03-03

I have a following problem. I have a dictionary dict_a. I would like to go through it and if some condition is met, then I would like to pop the item from the dict_a. When I try this:

for key in dict_a.keys():
     if # some condition:
         dict_a.pop(key)            

I got an error

RuntimeError: dictionary changed size during iteration. 

Is there a more pythonic way how to do it than this below?

dict_b = dict_a.copy()

for key in dict_a.keys():
     if # some condition:
         dict_b.pop(key)  

dict_a = dict_b.copy()

CodePudding user response:

You could make a list from dict_a keys beforehand:

for key in list(dict_a):
     if # some condition:
         dict_a.pop(key)

CodePudding user response:

Try this instead. You can define your own logic using a regular function or a lambda function, if you wish.

def custom_filter_logic(item):
    # if some_condition, return False
    # define your logic below
    k, v = item[0], item[1]
    return v < 3

new_dict = {k: v for k, v in filter(custom_filter_logic, dict_a.items())}
  • Related