python字典中的5个最大值 [英] 5 maximum values in a python dictionary

查看:36
本文介绍了python字典中的5个最大值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一本这样的字典:

A = {'a':10, 'b':843, 'c': 39,.....}

我想获得这个 dict 的 5 个最大值并用这个存储一个新的 dict.为了获得我所做的最大值:

I want to get the 5 maximum values of this dict and store a new dict with this. To get the maximum value I did:

max(A.iteritems(), key=operator.itemgetter(1))[0:]

也许这是一项简单的任务,但我坚持了很长时间.请帮忙!!!

Perhaps it is an easy task, but I am stuck on it for a long time. Please help!!!

推荐答案

你已经接近了.您可以使用 sorted 对列表进行排序[docs] 并取前五个元素:

You are close. You can sort the list using sorted [docs] and take the first five elements:

newA = dict(sorted(A.iteritems(), key=operator.itemgetter(1), reverse=True)[:5])

另见:Python 排序方法

这篇关于python字典中的5个最大值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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