我有一个字典,其中每个键都有一个字典作为它的值(嵌套字典都具有相同的键集)。我试图找到与子键上的两个条件关联的键:给定另一个子键的子键的最大值为True。
例如:
d = {'key1' : {'subkey1' : True, 'subkey2' : 4},
'key2' : {'subkey1' : True, 'subkey2' : 8},
'key3' : {'subkey1' : False, 'subkey2' : 1},
'key4' : {'subkey1' : False, 'subkey2' : 9} }
我希望结果为“ key2”,因为它是“ subkey2”的最大值,其中“ subkey1”为True。
我的诱惑是将所有内容放入数组中并找到与这些值关联的索引,但我的印象是,无需添加更多变量来存储相同信息就可以实现。我认为可能是更好的方法,因为我是Python的新手。
有什么建议么?谢谢!
最佳答案
这是您问题的可选实现。
首先,用True过滤所有subkey1。
其次,从过滤后的字典中找到subkey2中的最大值。
d = {'key1' : {'subkey1' : True, 'subkey2' : 4},
'key2' : {'subkey1' : True, 'subkey2' : 8},
'key3' : {'subkey1' : False, 'subkey2' : 1},
'key4' : {'subkey1' : False, 'subkey2' : 9} }
max_d = {v["subkey2"]:{k:v} for k,v in d.items() if v["subkey1"]} # create new dictionary that the key is the value from subkey2 and the value is the original key and value.
max_int = max(max_d.keys(), key=int) # get the max key
print (max_d[max_int]) # print the maximum
>>> {'key2': {'subkey1': True, 'subkey2': 8}}