Home > Net >  Nested list of objects get all keys recursively
Nested list of objects get all keys recursively

Time:04-13

How can i get all the keys by recursing the following nested dict.

   DICTS = {
        'test/test': [
            {
                'test1/test1': [{'test3/test3': []}],
                'test2/test2': [],
                'test4/test4': []
            }
        ],
        'test8/test8': [
            {
                'test1/test5': [
                    {
                        'test6/test6': []
                    }
                ],
                'test7/test7': [],
                'test7/test7': []
            }
        ],
    }

For example call a function by giving the key 'test/test' and get a list of values:

my_recursive_func('test/test')

test1/test1
test3/test3
test2/test2
test4/test4

CodePudding user response:

You basically have two cases:

Case 1 when your dictionary is in another dictionary

Case 2 when your dictionary is in a dictionary array

For every key that you have in your dictionary, you put that key into keys array and recall the function get_keys with the nested dictionary. If your nested dictionary is a list, you return get_keys() for every item in your list.

def get_keys(dictionary):
    keys = []
    if isinstance(dictionary, list):
        for item in dictionary:
            keys.extend(get_keys(item))
    elif isinstance(dictionary, dict):
        for key in dictionary:
            keys.append(key)
            keys.extend(get_keys(dictionary[key]))
    return keys


print(get_keys(DICTS["test/test"]))

outputs

['test1/test1', 'test3/test3', 'test2/test2', 'test4/test4']

This solution should work for any given structure.

CodePudding user response:

This solution would be valid only for your specific data structure.

def my_recursive_func(data):
    result = []
    
    if isinstance(data, list):
        for datum in data:
            result.extend(my_recursive_func(datum))
            
    elif isinstance(data, dict):
        for key, value in data.items():
            result.append(key)
            result.extend(my_recursive_func(value))
            
    return result
my_recursive_func(DICTS['test/test'])
> ['test1/test1', 'test3/test3', 'test2/test2', 'test4/test4']
  • Related