Home > Software engineering >  Get keys of all child dictionaries
Get keys of all child dictionaries

Time:06-05

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

CodePudding user response:

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

CodePudding user response:

keys = []

for key, val in data.items():
    keys.append(key)
    if isinstance(val, dict):
        item = val
        while True:
            for k, v in item.items():
                keys.append(k)
                if isinstance(v, dict):
                    item = v
                    break
            else:
                break

print(keys)

This outputs:

['key1', 'keya', 'keyc', 'key2', 'keyi', 'keyii']
  • Related