How to delete items from a dictionary while iterating over it?

前端 未结 10 1413
一生所求
一生所求 2020-11-22 17:22

Is it legitimate to delete items from a dictionary in Python while iterating over it?

For example:

for k, v in mydict.iteritems():
   if k == val:
           


        
10条回答
  •  没有蜡笔的小新
    2020-11-22 17:46

    There is a way that may be suitable if the items you want to delete are always at the "beginning" of the dict iteration

    while mydict:
        key, value = next(iter(mydict.items()))
        if should_delete(key, value):
           del mydict[key]
        else:
           break
    

    The "beginning" is only guaranteed to be consistent for certain Python versions/implementations. For example from What’s New In Python 3.7

    the insertion-order preservation nature of dict objects has been declared to be an official part of the Python language spec.

    This way avoids a copy of the dict that a lot of the other answers suggest, at least in Python 3.

提交回复
热议问题