快速回答
排序工作:
>>> dict(sorted(data.items(), key=lambda x: x[1]['score'], reverse=True)[:2])
{'Shewag': {'out': 150, 'score': 12000},
'sachin': {'out': 100, 'score': 15000}}
In Steps
您对项目进行排序:
>>> sorted(data.items())
[('Dhoni', {'out': 80, 'score': 8000}),
('Shewag', {'out': 150, 'score': 12000}),
('sachin', {'out': 100, 'score': 15000})]
这按名称的字母顺序排序。
Using a key
函数定义为lambda
排序依据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})]
Use 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})])