简体   繁体   English

如何在字典的字典中找到具有最高值的键?

[英]how to find the key with the highest value in a dict of dicts?

I have a dict of dicts.我有一个字典。

Example:例子:

scores[i][subentity_type] = the_score

It looks like this:它看起来像这样:

scores = {0:{'SD':1,'ED':2},1:{'SD':0.5,'ED':3}}

so i would want a function that returns所以我想要一个返回的函数

'SD' --> 0
'ED' --> 1

for each subentity_type , I want to find the key i with the highest score.对于每个subentity_type ,我想找到得分最高的键i do you have an idea if there is a python function to provide this?你知道是否有一个python函数来提供这个吗? thanks!谢谢!

There is a max() method that accepts an array and determines the max value.有一个max()方法接受一个数组并确定最大值。

You can turn the values of a dict into a list with mydict.values() or as a generator v for v in mydict.values() .您可以使用mydict.values()将 dict 的值转换为列表,或者作为mydict.values()中的v for v in mydict.values()生成器v for v in mydict.values()

You however have a dict of dicts.但是,您有一个字典。 You can iterate through it with for dictofdict in mydict.values()您可以for dictofdict in mydict.values()使用for dictofdict in mydict.values()遍历它

-> Resulting code: -> 结果代码:

>>> mydict={'a': {'aa': 3, 'ab':7},
...         'b': {'ba': 5, 'bb':9}}
>>> [v for dictofdict in mydict.values() for v in dictofdict.values()]
[3, 7, 5, 9]
>>> max([v for dictofdict in mydict.values() for v in dictofdict.values()])
9

A dict of dict where you get the highest value.获得最高值的 dict 的 dict。

Since you haven't actually explained how your final output should look like but I think you can sort the dict items based on values and get the key with highest value.由于您实际上还没有解释最终输出的样子,但我认为您可以根据值对dict项进行排序并获得具有最高值的键。 Taking the example for Tin's answer以 Tin 的回答为例

mydict={'a': {'aa': 3, 'ab':7},
        'b': {'ba': 5, 'bb':9}}

new_dict ={}

for k in mydict.keys():
    new_dict[k] = sorted(mydict[k].items(), key= lambda v:-v[1])[0][0] 

#new_dict = {'a': 'ab', 'b': 'bb'} #new_dict = {'a': 'ab', 'b': 'bb'}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM