How to solve dictionary changed size during iteration error?

后端 未结 8 1986
滥情空心
滥情空心 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:46

    Here is one way to solve it:

    1. From the dictionary, get a list of keys, sorted by value
    2. Since the first key in this list has the smallest value, you can do what you want with it.

    Here is a sample:

    # A list of grades, not in any order
    grades = dict(John=95,Amanda=89,Jake=91,Betty=97)
    
    # students is a list of students, sorted from lowest to highest grade
    students = sorted(grades, key=lambda k: grades[k])
    
    print 'Grades from lowest to highest:'
    for student in students:
        print '{0} {1}'.format(grades[student], student)
    
    lowest_student = students[0]
    highest_student = students[-1]
    print 'Lowest grade of {0} belongs to {1}'.format(grades[lowest_student], lowest_student)
    print 'Highest grade of {0} belongs to {1}'.format(grades[highest_student], highest_student)
    

    The secret sauce here is in the sorted() function: instead of sorting by keys, we sorted by values.

提交回复
热议问题