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

2024-05-19 22:47:54 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一本字典,像:

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()

在这里游荡没有成功。

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

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

有人能分享一些关于这个的想法吗!!!

输出如下:

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

注:应该是前n名球员,例如我需要前两名,但它可以改变后阶段。


Tags: keyinfordata字典valuewithkeys
3条回答

是的,您可以通过lambda方法的key参数轻松地完成此操作。请参阅此link以获得更清晰的信息

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

print sorted(data.keys(), key = lambda x:data[x]["score"], reverse = True)
>>> ['sachin', 'Shewag', 'Dhoni']

为了只得到前两个结果,您可以尝试列表切片作为lst[: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})]

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

使用由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})])

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

方法是:

  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)

相关问题 更多 >