简体   繁体   中英

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 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'] .

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 ? I'm thinking another for loop but can't wrap my head around how this would be executed.

I've also tried: [list(my_dict['DICT'][level]) for level in levels] but the output isn't exactly correct.

Given my_list and my_dict , my ideal output for this minimum reproducible example should be: ['level_2b', 'level_2c'] .

Of course, the code is to be functional with more than 1 items in my_list as well. 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())

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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