[英]How to fix this python error? RuntimeError: dictionary changed size during iteration
[英]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)
在上面的代碼中,我想刪除字典中的最小值元素。
我能夠從字典中刪除單個最小元素。 但是,如果字典中有多個相同的最低價值元素,我想刪除所有這些最低價值元素。
您可以對students.values()
使用min
來獲取最小值,
然后收集所有具有相同值的鍵,
然后將del
用於所有這些鍵,如下所示:
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)
最可靠的方法不是刪除條目,而是創建沒有它們的新dict
。 使用dict
理解來過濾出所有得分最低的條目:
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)
如果要修改初始dict
,請創建一個單獨的條目列表以進行迭代:
...
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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.