0
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.

vvvvv
  • 25,404
  • 19
  • 49
  • 81
  • 1
    Possible duplicate of [How to delete items from a dictionary while iterating over it?](https://stackoverflow.com/questions/5384914/how-to-delete-items-from-a-dictionary-while-iterating-over-it) – Calder White Jul 14 '19 at 14:54

2 Answers2

0

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)
Adam.Er8
  • 12,675
  • 3
  • 26
  • 38
0

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)
MisterMiyagi
  • 44,374
  • 10
  • 104
  • 119