python输出字典的前十项_Python:以值作为字典获取前n个键

该博客介绍了如何在Python中根据字典值的score属性对字典进行排序,并获取排名前n的键值对。通过使用`sorted()`函数结合`lambda`表达式进行排序,然后通过切片选取前n项,最后转化为字典。还提供了一个名为`get_top_players`的函数,可以根据需要返回`OrderedDict`或普通字典。
Python3.8

Python3.8

Conda
Python

Python 是一种高级、解释型、通用的编程语言,以其简洁易读的语法而闻名,适用于广泛的应用,包括Web开发、数据分析、人工智能和自动化脚本

快速回答

分类工作:>>> 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})])

您可能感兴趣的与本文相关的镜像

Python3.8

Python3.8

Conda
Python

Python 是一种高级、解释型、通用的编程语言,以其简洁易读的语法而闻名,适用于广泛的应用,包括Web开发、数据分析、人工智能和自动化脚本

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值