简体   繁体   中英

how to fix “ runtime error :dictionary changed size during iteration ” in python 3.7

if __name__ == '__main__':

    students = {}

    for _ in range(int(input())):
        name = input()
        score = float(input())
        seq = {name: score}
        students.update(seq)
        a = min(students, key=students.get)

    for key, value in students.items():
        while a == min(students, key=students.get):
            del students[min(students, key=students.get)]

    print(students)

In the above code, I would like to remove the minimum valued element in the dictionary.

I am able to remove a single minimum element from the dictionary. But I want to remove all such minimum valued elements if there are more than one same minimum valued elements in the dictionary.

you can use min on students.values() to get the minimum value,

then collect all keys that have this same value,

then use del for all these keys, like this:

if __name__ == '__main__':

    students = {}

    for _ in range(int(input())):
        name = input()
        score = float(input())
        seq = {name: score}
        students.update(seq)

    min_val = min(students.values())
    all_keys_with_min_val = [key for key, value in students.items() if value == min_val]

    for key in all_keys_with_min_val:
        del students[key]

    print(students)

The most robust approach is not to remove entries, but to create a new dict without them. Use a dict comprehension to filter out all entries matching the lowest score:

if __name__ == '__main__':
    students = {}
    for _ in range(int(input())):
        name = input()
        score = float(input())
        students[name] = score  # store directly without update
    min_score = min(students.values())  # calculate minimum only once

    students = {
        name: score for name, score in students.items()
        if score != min_score  # only keep students above minimum score
    }
    print(students)

If you want to modify your initial dict , create a separate list of entries to iterate on:

...
min_score = min(students.values())  # calculate minimum only once

min_score_students = [name for name, score in students.items() if score == min_score]
for student in min_score_students:
    del students[key]
print(students)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM