Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Nested list of objects get all keys recursively

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading