所以我有这段代码
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'等等。
到目前为止我已经
了for value in list1:
m = max(dictionary, key=lambda v: dictionary[v][value])
print(m + "\n")
但是只有在字典中的所有键中都存在相同的子键时,这才有效。关于该怎么做的任何想法?
答案 0 :(得分:6)
缺少密钥时使用float('-inf')
:
m = max(dictionary, key=lambda v: dictionary[v].get(value, float('-inf')))
负无穷大保证小于字典中的任何现有值,确保忽略具有特定键缺失的嵌套字典。
演示:
>>> 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
但是,如果您只翻转一次所有字典值,它会更有效率:
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()
。
演示:
>>> 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