简体   繁体   English

Pythonic方法找到与嵌套字典相关的键

[英]Pythonic way to find the key associated with nested dictionary

I have a dictionary where each key has a dictionary as its value (the nested dictionaries all have the same set of keys). 我有一个字典,其中每个键都有一个字典作为其值(嵌套字典都有相同的键集)。 I'm trying to find the key associated with two conditions on subkeys: the max value of a subkey given another subkey is True. 我试图找到与子键上的两个条件相关联的键:给定另一个子键的子键的最大值为True。

For example: 例如:

d = {'key1' : {'subkey1' : True,  'subkey2' : 4},
     'key2' : {'subkey1' : True,  'subkey2' : 8},
     'key3' : {'subkey1' : False, 'subkey2' : 1},
     'key4' : {'subkey1' : False, 'subkey2' : 9} }

I would want the result to be 'key2' because it is the max value of 'subkey2' where 'subkey1' is True. 我希望结果为'key2',因为它是'subkey2'的最大值,其中'subkey1'为True。

My temptation is to put everything into an array and find the indexes associated with these values, but I have the impression this can be accomplished without adding more variables to store the same information. 我的诱惑是将所有内容放入一个数组中并找到与这些值相关联的索引,但我的印象是,这可以在不添加更多变量来存储相同信息的情况下完成。 I thought there might be a better way since I'm relatively new to Python. 我认为可能有更好的方法,因为我对Python比较新。

Any suggestions? 有什么建议么? Thanks! 谢谢!

This is an optional implementation to your issue. 这是您的问题的可选实现。

First, filter all subkey1 with True. 首先,使用True过滤所有subkey1。

Second, find from the filtered dictionary the max value within subkey2. 其次,从过滤字典中查找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}}

It's a bit convoluted but how about this: 这有点令人费解但是这个怎么样:

print(d[max({key:d[key] for key in [k for k in d.keys() if d[k]['subkey1'] is True]})])

First we make a list of main keys that have subkey1 as True, then for each of them we rebuild a dictionary of key value pairs and we take the key with the max value 首先,我们创建一个主键的列表,其中subkey1为True,然后为每个主键重建一个键值对的字典,我们采用最大值的键

Haven't fully tested this so please do at your end if you consider it worth the time. 尚未对此进行全面测试,如果您认为值得花时间,请在最后进行测试。

What you might need is reduce from functools 你可能需要的是reduce functools

Here is the solution you might be looking for: 以下是您可能正在寻找的解决方案:

from functools import reduce
import operator

d = {'key1' : {'subkey1' : True,  'subkey2' : 4},
     'key2' : {'subkey1' : True,  'subkey2' : 8},
     'key3' : {'subkey1' : False, 'subkey2' : 1},
     'key4' : {'subkey1' : False, 'subkey2' : 9} }
maxsum=0
for k in d:
    if reduce(operator.getitem, [k,'subkey1'], d):
        value = (reduce(operator.getitem, [k,'subkey2'], d))
        if maxsum<value:
            maxsum=value
print(maxsum)

Basically what this reduce(operator.getitem, [k,'subkey1'], d) does is it takes values from the sub dictionary. 基本上这个reduce(operator.getitem, [k,'subkey1'], d)作用是从子字典中获取值。 For example: 例如:

d = {'John' : {'Male' : True,  'age' : 41}}
reduce(operator.getitem, ['John','Male'], d)

output: 输出:

True

Here reduce traverses through John-->Male and gets the result as True 这里通过John减少遍历 - > Male并将结果True

We can also give lists as argument. 我们也可以将列表作为参数。 Take a look at this, 看看这个,

from functools import reduce
import operator

d = {'John' : {'Male' : True,  'age' : 41},
         'Vishnu':{'Male':True ,'age':23}}
chklist1 = ['John','Male']
chklist2 = ['Vishnu','age']
print(reduce(operator.getitem, chklist1, d))
print(reduce(operator.getitem, chklist2, d))

output: 输出:

True
23

You can't always expect the dict to be a dict of dict. 你不能总是期望这个词典是dict的词典。 It can be say a dict of a dict of a dict of a dict. 它可以说是一个dict dict dict的字典。 (Who knows? things happen!) (谁知道?事情发生了!)

from functools import reduce
import operator

d = {
    "John":{
        "Age": 23,
        "Sex": 'M',
        "Country": 'USA'
        },
    "Vishnu":{
        "Age": 1,
        "Country": {
            "India": 'TamilNadu',
            "USA": None,
            "South Africa": None
        }
        }
}
chklist1 = ['John','Age']
chklist2 = ['Vishnu','Country','India']
print(reduce(operator.getitem, chklist1, d))
print(reduce(operator.getitem, chklist2, d))

output: 输出:

23
TamilNadu

So now coming back to your problem: 所以现在回到你的问题:

for k in d:
    if reduce(operator.getitem, [k,'subkey1'], d):
        value = (reduce(operator.getitem, [k,'subkey2'], d))
        if maxsum<value:
            maxsum=value
print(maxsum)

For every key k which would be your key1,key2,... and so on. 对于每个键k ,它将是你的key1,key2,...等等。 First reduce(operator.getitem, [k,'subkey1'], d) checks if the value contained within it is True or False . 首先, reduce(operator.getitem, [k,'subkey1'], d)检查其中包含的值是True还是False Only proceeds if it is True 只有在True时才会继续

Then maxsum is set to the second item in sub_dict of dict. 然后将maxsum设置为dict的sub_dict中的第二项。 For every key it is checked and if another value greater than the current one is found the value is changed else it goes on. 检查每个键,如果找到另一个大于当前值的值,则更改该值,否则继续。 Until you find the maximum value which you can print out. 直到找到可以打印出的最大值。

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

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