查找嵌套字典中的最大值并返回键 [英] Find Maximum Value in Nested Dictionary and return Key

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

问题描述

所以我有这个代码块

dictionary = {
  'key1': {'a': 1, 'b': 2, 'c': 10}, 
  'key2': {'d': 1, 'e': 1, 'c': 11}, 
  'key3': {'d': 2, 'b': 1, 'g': 12}}

list1 = (a,b,c)

我想做的是运行一个循环,找到列表中所有项目的最大值并返回该键。因此,例如,'c'的最大值将返回'key2','b'的最大值将返回'key1'等。

What I want to do is run a loop that finds the maximums of all the items in the list and returns the key. So for example, the maximum of 'c' would return 'key2', the maximum of 'b' would return 'key1', etc.

到目前为止, / p>

So far I have

for value in list1:
     m = max(dictionary, key=lambda v: dictionary[v][value])
     print(m + "\n")

但这只有在相同子项存在于字典中的所有键中。任何想法要做什么?

But this only works if the same subkey exists in all keys in the dictionary. Any ideas on what to do?

推荐答案

使用 float(' - inf')当键丢失时:

m = max(dictionary, key=lambda v: dictionary[v].get(value, float('-inf')))

负无穷大保证比任何字典中的现有价值,确保忽略了具体密钥的嵌套字典。

Negative infinity is guaranteed to be smaller than any existing value in the dictionaries, ensuring that nested dictionaries with the specific key missing are ignored.

演示:

>>> dictionary = {
...   'key1': {'a': 1, 'b': 2, 'c': 10}, 
...   'key2': {'d': 1, 'e': 1, 'c': 11}, 
...   'key3': {'d': 2, 'b': 1, 'g': 12}}
>>> list1 = ('a', 'b', 'c')
>>> for value in list1:
...      print(value, max(dictionary, key=lambda v: dictionary[v].get(value, float('-inf'))))
... 
a key1
b key1
c key2

然而,如果您只是循环使用所有字典值,那么效率会更高:

However, it'll be more efficient if you looped over all your dictionary values just once instead:

maximi = dict.fromkeys(list1, (None, float('-inf')))

for key, nested in dictionary.items():
    for k in nested.keys() & maximi:  # intersection of keys
        if maximi[k][0] is None or dictionary[maximi[k][0]][k] < nested[k]:
            maximi[k] = (key, nested[k])

for value in list1:
    print(value, maximi[value][0])

这是假设你使用的是Python 3;在Python 2中,将 .items()替换为 .iteritems() .keys ) .viewkeys()

That's presuming you are using Python 3; in Python 2, replace .items() with .iteritems() and .keys() with .viewkeys().

演示:

>>> maximi = dict.fromkeys(list1, (None, float('-inf')))
>>> for key, nested in dictionary.items():
...     for k in nested.keys() & maximi:  # intersection of keys
...         if maximi[k][0] is None or dictionary[maximi[k][0]][k] < nested[k]:
...             maximi[k] = (key, nested[k])
... 
>>> maximi
{'a': ('key1', 1), 'b': ('key1', 2), 'c': ('key2', 11)}
>>> for value in list1:
...     print(value, maximi[value][0])
... 
a key1
b key1
c key2

这篇关于查找嵌套字典中的最大值并返回键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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