custom dict that allows delete during iteration

后端 未结 7 1948
时光说笑
时光说笑 2020-12-08 09:53

UPDATED based on Lennart Regebro\'s answer

Suppose you iterate through a dictionary, and sometimes need to delete an element. The following is very efficient:

<
7条回答
  •  囚心锁ツ
    2020-12-08 10:41

    This could work as a compromise between the two examples - two lines longer than the second one, but shorter and slightly faster than the first. Python 2:

    dict_ = {k : random.randint(0, 40000) for k in range(0,200000)}
    
    dict_remove = [k for k,v in dict_.iteritems() if v < 3000]
    for k in dict_remove:
        del dict_[k]
    

    Split into a function and it's down to one line each call (whether this is more readable or not is your call):

    def dict_remove(dict_, keys):
        for k in keys:
            del dict_[k]
    
    dict_remove(dict_, [k for k,v in dict_.iteritems() if v < 3000])
    

    Regardless of where the code is stored, you'll have to store the keys needing deletion somewhere. The only way around that is using generator expressions, which will explode the moment you delete a key for the first time.

提交回复
热议问题