Back

Explore Courses Blog Tutorials Interview Questions
0 votes
3 views
in Python by (47.6k points)

I want to 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(): 

for key1, value1 in dictionary.items(): 

if key1!= key and value > value1: 

dictionary.pop(key) 

print (dictionary)

Which results in

RuntimeError: dictionary changed size during iteration

How can I avoid this error?

1 Answer

0 votes
by (106k points)

It looks like you are looking for the smallest value in the dictionary, so for that, you can do something like follows:

min(dictionary.values())

If you cannot use min, you can use sorted:

sorted(dictionary.values())[0]

Related questions

0 votes
4 answers
0 votes
4 answers
0 votes
1 answer

Browse Categories

...