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

Get keys of all child dictionaries

I have a dictionary of this kind where the values are dictionaries as well the dictionaries can have nested dictionaries in them. like this:

data = {'key1': {
              'keya':{ 
                      'keyc': None
                      }    
              'keyb': None
                       
                }
        'key2': {
               'keyi':None, 
               'keyii': None
                }
       }

The dictionaries can be many (we don’t know how many dictionaries can be there inside the values). How can I get all keys in all values like this?

['key1', 'key2', 'keya', 'keyb', 'keyi', 'keyii']

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 could get all the keys using recursion

def get_all_keys_rec(dic):
    keys = [key for key in dic]
    for val in dic.values():
        if type(val)==dict:
            inner_keys = get_all_keys_rec(val)
            keys.extend(inner_keys)
    return keys

print(get_all_keys_rec(data))

output:

['key1', 'key2', 'keya', 'keyb', 'keyc', 'keyi', 'keyii']
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