custom dict that allows delete during iteration

后端 未结 7 1950
时光说笑
时光说笑 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:49

    Python 3.2 has such dict in the stdlib:

    #!/usr/bin/env python3
    from collections import OrderedDict as odict
    
    d = odict(zip(range(3), "abc"))
    print(d)
    for k in d:
        if k == 2:
           del d[k]
    print(d)
    

    Output

    OrderedDict([(0, 'a'), (1, 'b'), (2, 'c')])
    OrderedDict([(0, 'a'), (1, 'b')])
    

    Iteration is performed over a linked list, see __iter__() method implementation. The deletion is safe (in Python 3.2) even though items are weak references.

    0 讨论(0)
提交回复
热议问题