[英]How to get list of all inner level nested keys in python dictionary corresponding to values in a different list?
Suppose I have a list similar to my_list = ['level_1b']
.假设我有一个类似于my_list = ['level_1b']
。 My dictionary resembles:我的字典类似于:
my_dict= {
'DICT':{
'level_1a':{
'level_2a':{}
},
'level_1b': {
'level_2b':{},
'level_2c':{}
}
}
The current code I have extracts all the inner level nested keys within this dictionary:我的当前代码提取了此字典中的所有内部级别嵌套键:
[key for level in my_dict["DICT"].values() for key in level]
with output as ['level_2a', 'level_2b', 'level_2c']
. [key for level in my_dict["DICT"].values() for key in level]
输出为['level_2a', 'level_2b', 'level_2c']
。
How would I go about filtering this list into only extracting the level 2 values corresponding to the level 1 values that I include in my_list
?我将如何过滤此列表以仅提取与包含在my_list
的级别 1 值相对应的级别 2 值? I'm thinking another for
loop but can't wrap my head around how this would be executed.我正在考虑另一个for
循环,但无法理解这将如何执行。
I've also tried: [list(my_dict['DICT'][level]) for level in levels]
but the output isn't exactly correct.我也试过: [list(my_dict['DICT'][level]) for level in levels]
但输出并不完全正确。
Given my_list
and my_dict
, my ideal output for this minimum reproducible example should be: ['level_2b', 'level_2c']
.鉴于my_list
和my_dict
,这个最小可重现示例的理想输出应该是: ['level_2b', 'level_2c']
。
Of course, the code is to be functional with more than 1 items in my_list
as well.当然,代码也要在my_list
有 1 个以上的项目时起作用。 Thank you in advance.先感谢您。
Try it:尝试一下:
[(nested_key) for key, value in my_dict["DICT"].items() for nested_key in value.keys() if key in my_list]
Output:输出:
['level_2b', 'level_2c']
This should work.这应该有效。 Just not a list comprehension anymore, thus easier to think about.只是不再是列表理解,因此更容易思考。
level2_keys = []
for level1_key in my_list:
level2_keys.extend(my_dict["DICT"][level1_key].keys())
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.