'How to pop from a dict while looping?

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()


Solution 1:[1]

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())}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 JianXu Chen