How to solve dictionary changed size during iteration error?

后端 未结 8 1965
滥情空心
滥情空心 2020-12-06 01:40

I want pop out all the large values and its keys in a dictionary, and keep the smallest. Here is the part of my program

for key,value in dictionary.items():
         


        
8条回答
  •  眼角桃花
    2020-12-06 01:52

    If you want to just keep the key with the smallest value, I would do it by first finding that item and then creating a new dictionary containing only it. If your dictionary was d, something like this would do that in one line:

    d = dict((min(d.items(), key=lambda item: item[1]),))
    

    This will not only avoid any issues about updating the dictionary while iterating it, it is probably faster than removing all the other elements.

    If you must do the modifications in-place for some reason, the following would work because it makes a copy of all the keys before modifying the dictionary:

    key_to_keep = min(d.items(), key=lambda item: item[1])[0]
    
    for key in list(d):
        if key != key_to_keep:
            d.pop(key)
    

提交回复
热议问题