Ricardo Francois
Ricardo Francois

Reputation: 792

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.

Upvotes: 1

Views: 777

Answers (2)

Cornelius Roemer
Cornelius Roemer

Reputation: 8158

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())

Upvotes: 2

voldr
voldr

Reputation: 392

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

Upvotes: 3

Related Questions