Python:使用“值"作为字典获取前n个键 [英] Python: Get top n key's with Value as dictionary

查看:295
本文介绍了Python:使用“值"作为字典获取前n个键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个像这样的字典

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

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

I want to get two players whose score are in top.

所以我尝试过: key =(键的键,如果value ['score']>'value'在dd.items()中的值).next()

缠绕在这里没有成功.

尝试使用链接:顶部字典中以元组为键的n个键的值最高

作为Python的新手无法解决完美的解决方案.

As newbie to Python couldn't get around the perfect solution.

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

Can someone share some idea on this!!!

输出类似:

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

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

Note: Should be top n player, just for example I need top two but It can be changed later stage.

推荐答案

快速解答

排序工作:

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

You sort the items:

>>> sorted(data.items())
[('Dhoni', {'out': 80, 'score': 8000}),
 ('Shewag', {'out': 150, 'score': 12000}),
 ('sachin', {'out': 100, 'score': 15000})]

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

This sorts by the names in alphabetical order.

使用由 lambda 定义的 key 函数按得分排序:

Using a key function defined with lambda sorts by 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 首先获得最大的一个:

Use reverse to get the largest one first:

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 将元组列表转换为字典:

Finally, take only the two first items with slicing and convert the list of tuples into a dictionary with 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 来保留订单:

Since a dictionary has no order, you only know that you have two players with top most scores. There is no notion who is first or second. If need this, you can either keep the list of tuples or convert into an OrderedDict to preserve the order:

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

正确执行

要使其具有更高的可重用性,您可以编写一个函数:

Do It Properly

To make it bit more reusable, you can write a function:

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)

​

现在您可以将其与数据一起使用:

Now you can use it just with your data:

>>> get_top_players(data)
{'Shewag': {'out': 150, 'score': 12000},
 'sachin': {'out': 100, 'score': 15000}}

或设置其他数量的顶级玩家:

or set a different number of top players:

>>> 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个键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆