簡體   English   中英

從字典中的鍵-值對中刪除值

[英]Removing values from key - value pairs in a dictionary

我有一本字典,其中包含學生的姓名和他們在測驗中的分數:

scores = {'Sam': ['8'], 'Ben': ['8', '10', '9' ,'4'], 'Jack': ['6', '5'], 'Tim': ['9', '10', '7', '9']}

我想檢查字典中每個鍵值對中值的數量,如果有3個以上的值,則刪除1個值。

我已經試過了:

if len(scores) > 3:
  dictionary.pop(1)

但是,這會導致關鍵錯誤。

有關如何執行此操作的任何想法?

您要從值中刪除 ,而不是條目。 您想限制那些:

for key in scores:
    if len(scores[key]) > 3:
        scores[key] = scores[key][:3]

這將保留三個值。 這將取決於您如何添加這些值。 您可能想保留最后 3個值:

for key in scores:
    if len(scores[key]) > 3:
        scores[key] = scores[key][-3:]

但是,您實際上並不需要len()測試。 如果您的項目較少,切片將永遠不會引發錯誤,因此您可以使用:

for key in scores:
    scores[key] = scores[key][-3:]

如果項目較少,它將繼續工作。

您甚至可以使用字典理解功能簡單地重新生成字典:

scores = {student: values[-3:] for student, values in scores.items()}

該演示顯示了最后一種方法:

>>> scores = {'Sam': ['8'], 'Ben': ['8', '10', '9' ,'4'], 'Jack': ['6', '5'], 'Tim': ['9', '10', '7', '9']}
>>> {student: values[-3:] for student, values in scores.items()}
{'Tim': ['10', '7', '9'], 'Ben': ['10', '9', '4'], 'Jack': ['6', '5'], 'Sam': ['8']}

你不需要pop你可以只使用切片:

>>> scores = {'Sam': ['8'], 'Ben': ['8', '10', '9' ,'4'], 'Jack': ['6', '5'], 'Tim': ['9', '10', '7', '9']}
>>> scores =dict((i,j[1:]) if len(j)>3 else (i,j) for i,j in scores.items())
>>> scores
{'Tim': ['10', '7', '9'], 'Ben': ['10', '9', '4'], 'Jack': ['6', '5'], 'Sam': ['8']}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM