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

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

问题描述

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

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

在字典中的所有值中,90是最高的值,我需要检索与之对应的键。



什么是这样做的可能方式。



注意:


  1. 键和/或值不符合字典的顺序。程序不断向空字典添加新的(键值)对。


  2. max(value)可能有多个键
    Ex :上面的dict1应该返回['j','g']
    以上的dict2应该返回'j'



    a)如果dict只有一个对应于max(value),那么结果应该只是一个字符串(即Key)
    b)如果dict有多个键对应于max(value),那么结果应该是字符串列表(iekeys)。



解决方案

您可以:

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


Let's consider a sample dictionary 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}

Of all the values in the dictionary, 90 is the highest one, I need to retrieve the key corresponds to it.

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

Note:

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

  2. There might be more than one key for max(value) Ex: dict1 above should return ['j', 'g'] dict2 above should return 'j'

    a) If dict has only one key corresponds to max(value) then the result should be just a string (i.e. Key) b) If dict has more than one key corresponds to max(value) then the result should be list of strings (i.e.keys).

解决方案

You can do:

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天全站免登陆