快速回答
分类工作:>>> dict(sorted(data.items(), key=lambda x: x[1]['score'], reverse=True)[:2])
{'Shewag': {'out': 150, 'score': 12000},
'sachin': {'out': 100, 'score': 15000}}
分步
您可以对项目进行排序:>>> sorted(data.items())
[('Dhoni', {'out': 80, 'score': 8000}),
('Shewag', {'out': 150, 'score': 12000}),
('sachin', {'out': 100, 'score': 15000})]
这是按名字的字母顺序排序的。
使用由lambda定义的key函数按score排序:sorted(data.items(), key=lambda x: x[1]['score'])
[('Dhoni', {'out': 80, 'score': 8000}),
('Shewag', {'out': 150, 'score': 12000}),
('sachin', {'out': 100, 'score': 15000})]
使用reverse首先得到最大的:sorted(data.items(), key=lambda x: x[1]['score'], reverse=True)
[('sachin', {'out': 100, 'score': 15000}),
('Shewag', {'out': 150, 'score': 12000}),
('Dhoni', {'out': 80, 'score': 8000})]
最后,通过切片只取前两个项,并使用dict将元组列表转换为字典:>>> dict(sorted(data.items(), key=lambda x: x[1]['score'], reverse=True)[:2])
{'Shewag': {'out': 150, 'score': 12000},
'sachin': {'out': 100, 'score': 15000}}
因为字典没有顺序,你只知道你有两个得分最高的玩家。不知道谁是第一或第二。如果需要,可以保留元组列表或转换为OrderedDict以保持顺序:>>> from collections import OrderedDict
>>> OrderedDict(sorted(data.items(), key=lambda x: x[1]['score'], reverse=True)[:2])
OrderedDict([('sachin', {'out': 100, 'score': 15000}),
('Shewag', {'out': 150, 'score': 12000})])
做得好
为了使其更具可重用性,您可以编写一个函数:from collections import OrderedDict
def get_top_players(data, n=2, order=False):
"""Get top n players by score.
Returns a dictionary or an `OrderedDict` if `order` is true.
"""
top = sorted(data.items(), key=lambda x: x[1]['score'], reverse=True)[:n]
if order:
return OrderedDict(top)
return dict(top)
现在您可以将其仅用于数据:>>> get_top_players(data)
{'Shewag': {'out': 150, 'score': 12000},
'sachin': {'out': 100, 'score': 15000}}
或者设置不同数量的顶级玩家:>>> get_top_players(data, n=3)
{'Dhoni': {'out': 80, 'score': 8000},
'Shewag': {'out': 150, 'score': 12000},
'sachin': {'out': 100, 'score': 15000}}
或者把它们整理好:>>> get_top_players(data, order=True)
OrderedDict([('sachin', {'out': 100, 'score': 15000}),
('Shewag', {'out': 150, 'score': 12000})])
该博客介绍了如何在Python中根据字典值的score属性对字典进行排序,并获取排名前n的键值对。通过使用`sorted()`函数结合`lambda`表达式进行排序,然后通过切片选取前n项,最后转化为字典。还提供了一个名为`get_top_players`的函数,可以根据需要返回`OrderedDict`或普通字典。

1万+


被折叠的 条评论
为什么被折叠?



