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

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

    With python3, iterate on dic.keys() will raise the dictionary size error. You can use this alternative way:

    Tested with python3, it works fine and the Error "dictionary changed size during iteration" is not raised:

    my_dic = { 1:10, 2:20, 3:30 }
    # Is important here to cast because ".keys()" method returns a dict_keys object.
    key_list = list( my_dic.keys() )
    
    # Iterate on the list:
    for k in key_list:
        print(key_list)
        print(my_dic)
        del( my_dic[k] )
    
    
    print( my_dic )
    # {}
    

提交回复
热议问题