获取与python dict中的max(value)对应的键 [英] Get the Key(s) corresponding to max(value) in python dict

查看:111
本文介绍了获取与python dict中的max(value)对应的键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们考虑以下(键,值)对的示例字典:

Let's consider sample dictionaries of (key, value) pairs as follows:

 dict1 = {'a' : 10, 'x' : 44, 'f': 34, 'h':89, 'j': 90, 'd': 28, 'g' : 90}
 dict2 = {'a' : 10, 'x' : 44, 'f': 34, 'h':89, 'j': 90, 'd': 28}

在词典中的所有值中,90是最高的.我需要检索与之对应的一个或多个键.

Of all the values in the dictionaries, 90 is the highest. I need to retrieve the key or keys that correspond to it.

完成此操作的可能方法是什么?哪一个是最有效的,为什么?

What are the possible ways to get this done? Which is the most efficient one, and why?

注意:

  1. 键和/或值与字典的顺序不符.该程序不断向字典添加新的(键,值)对.

  1. Keys and/or values are not in order for the dictionary. The program keeps adding new (key, value) pairs to the dictionary.

max(value)可能有多个键

There might be more than one key for max(value)

a)如果字典只有一个对应于max(value)的键,那么结果应该只是一个字符串(即Key).示例:上面的dict2应该返回'j'

a) If a dict has only one key corresponding to max(value), then the result should be just a string (i.e. Key). Example: dict2 above should return 'j'

b)如果一个字典具有多个与max(value)相对应的键,则结果应为字符串列表(即键).示例:上面的dict1应该返回['j','g']

b) If a dict has more than one key corresponding to max(value), then the result should be list of strings (i.e. keys). Example: dict1 above should return ['j', 'g']

推荐答案

您可以这样做:

maxval = max(dict.iteritems(), key=operator.itemgetter(1))[1]
keys = [k for k,v in dict.items() if v==maxval]

这篇关于获取与python dict中的max(value)对应的键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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