Home > Mobile >  Access dictionary specifing the nesting level
Access dictionary specifing the nesting level

Time:05-19

I have a multilevel dictionary, imagine something like:

raw_dict = {'a':{'b':{'c':[1,2,3]}},
            'd':{'e':{'f':{'g':[4,5,6]}}}}

Is it possible to access the keys of a specified nesting level?

That is, is there a way to do something like:

level = 1
keys_level_1 = list([a way to call the dictionary at specified nesting level])
print(keys_level_1)

which will return

['b', 'e']

this is similar, but not exactly what I want.

CodePudding user response:

Use a recursive function

def get_keys(dct, level):
    
    def get_(d, current=0):
        # check if we're at the level we want, yield if so
        if current==level:
            yield d
        # if not, move down one more level
        else:
            for v in d.values():
                # only move down if the value is a dict
                if isinstance(v, dict):
                    yield from get_(v, current 1)
                    
    return [x for s_l in get_(dct) for x in s_l]

raw_dict = {'a':{'b':{'c':[1,2,3]}},
            'd':{'e':{'f':{'g':[4,5,6]}}}}

get_keys(raw_dict, 0)
['a', 'd']
get_keys(raw_dict, 1)
['b', 'e']
get_keys(raw_dict, 2)
['c', 'f']
get_keys(raw_dict, 3)
['g']

CodePudding user response:

One possibility using a recursive function:

raw_dict = {'a':{'b':{'c':[1,2,3]}},
            'd':{'e':{'f':{'g':[4,5,6]}}}}

def get_level(d, level):
    from itertools import chain
    
    if level == 0:
        return list(d)
    else:
        return list(chain.from_iterable(get_level(d[item], level=level-1)
                          for item in d if isinstance(d[item], dict)))

get_level(raw_dict, level=1)

output: ['b', 'e']

other examples:

get_level(raw_dict, level=0)
['a', 'd']

get_level(raw_dict, level=1)
['b', 'e']

get_level(raw_dict, level=2)
['c', 'f']

get_level(raw_dict, level=3)
['g']

get_level(raw_dict, level=4)
[]
  • Related