Python:以值作为字典获取前n个键

新手上路,请多包涵

我有一本像这样的字典:

 data = {'sachin': {'score': 15000, 'out': 100},
        'Dhoni': {'score': 8000, out: 80},
        'Shewag': {'score': 12000, 'out': 150}}

我想得到两名得分最高的球员。

所以我试过: key = (key for key,value in dd.items() if value['score'] > 'value').next()

绕到这里没有成功。

尝试使用 link: top n keys with highest values in dictionary with tuples as keys

作为 Python 的新手,无法绕过完美的解决方案。

有人可以分享一些想法吗!!!

输出如:

 {'sachin':{'score':15000,'out':100},'Shewag':{'score':12000,'out':150}}

注意:应该是前 n 名玩家,例如我需要前两名,但可以在后期更改。

原文由 Sandy 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 703
2 个回答

快速回答

整理作品:

 >>> 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})]

这按名称的字母顺序排序。

使用 key 定义的函数 --- 按 score lambda 排序:

 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})])

原文由 Mike Müller 发布,翻译遵循 CC BY-SA 3.0 许可协议

你的链接是对的。您必须修改它以将其用于您的案例。

方法是:

  1. 降序排列
  2. 先得到n

您可以使用库 heapq

 >>> import heapq
>>> heapq.nlargest(2, data.keys(), key=lambda k: data[k]['score'])
['sachin', 'Shewag']

现在你可以创建一个新的 OrderedDict 来存储你的 dict

 import heapq
from collections import OderedDict
player_names = heapq.nlargest(2, data.keys(), key=lambda k: data[k]['score'])

ret = OrderedDict((x, data[x]) for x in player_names)

原文由 qvpham 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
logo
Stack Overflow 翻译
子站问答
访问
宣传栏