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

前端 未结 10 1389
一生所求
一生所求 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:43

    It's cleanest to use list(mydict):

    >>> mydict = {'one': 1, 'two': 2, 'three': 3, 'four': 4}
    >>> for k in list(mydict):
    ...     if k == 'three':
    ...         del mydict[k]
    ... 
    >>> mydict
    {'four': 4, 'two': 2, 'one': 1}
    

    This corresponds to a parallel structure for lists:

    >>> mylist = ['one', 'two', 'three', 'four']
    >>> for k in list(mylist):                            # or mylist[:]
    ...     if k == 'three':
    ...         mylist.remove(k)
    ... 
    >>> mylist
    ['one', 'two', 'four']
    

    Both work in python2 and python3.

提交回复
热议问题