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():
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)