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

标签 python dictionary

我有一本像这样的字典:

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名玩家,例如我需要前两名,但后期可以更改。

最佳答案

快速回答

作品排序:

>>> 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:以值作为字典获取前n个键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38218501/

相关文章:

python : Can Dictionary be used for indexing?

python - 剥离标签 python

python - 如何消除 "sys.excepthook is missing"错误?

python - 如何获取系列中1组的开始和结束索引?

python - 从字典列表中获取值列表

python - 访问字典python中列表中的项目

python - Scrapy 蜘蛛过早关闭

python - 遍历成对列表的元素

python - 在 Python 3.6+ 中按值对字典排序

python - javascript 的 _.where 在 python 中