从字典中的键 - 值对中删除值

时间:2015-03-07 18:29:13

标签: python 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)

然而,这会导致关键错误。

关于如何做到这一点的任何想法?

2 个答案:

答案 0 :(得分:1)

您要删除,而不是值中的条目。你想限制它们:

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

这样可以保留第一个 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']}

答案 1 :(得分:0)

你不需要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']}
相关问题