Skip to content Skip to sidebar Skip to footer

Get A List Of All Keys In Nested Dictionary

I want to get a list of all keys in a nested dictionary that contains lists and dictionaries. I currently have this code, but it seems to be missing adding some keys to the list an

Solution 1:

This should do the job:

defget_keys(dl, keys_list):
    ifisinstance(dl, dict):
        keys_list += dl.keys()
        map(lambda x: get_keys(x, keys_list), dl.values())
    elifisinstance(dl, list):
        map(lambda x: get_keys(x, keys_list), dl)

To avoid duplicates you can use set, e.g.:

keys_list = list( set( keys_list ) )

Example test case:

keys_list= []
d= {1:2, 3:4, 5: [{7: {9:1}}]}
get_keys(d,keys_list)printkeys_list>>>> [1, 3, 5, 7, 9]

Solution 2:

As it stands, your code ignores keys that lead to list or dict values. Remove the else block in your first for loop, you want to add the key no matter what the value is.

keys_list = []
defget_keys(d_or_l, keys_list):
    ifisinstance(d_or_l, dict):
        for k, v initer(sorted(d_or_l.iteritems())):
            ifisinstance(v, list):
                get_keys(v, keys_list)
            elifisinstance(v, dict):
                get_keys(v, keys_list)
            keys_list.append(k)   #  Altered lineelifisinstance(d_or_l, list):
        for i in d_or_l:
            ifisinstance(i, list):
                get_keys(i, keys_list)
            elifisinstance(i, dict):
                get_keys(i, keys_list)
    else:
        print"** Skipping item of type: {}".format(type(d_or_l))
    return keys_list

get_keys({1: 2, 3: 4, 5: [{7: {9: 1}}]}, keys_list) returns [1, 3, 9, 7, 5]

To avoid duplication, you could use a set datatype instead of a list.

Solution 3:

Updating @MackM's response to Python 3 as dict.iteritems has been deprecated (and I prefer to use f-strings over the .format{} styling):

keys_list = []
defget_keys(d_or_l, keys_list):
    ifisinstance(d_or_l, dict):
        for k, v initer(sorted(d_or_l.items())):  #  Altered line to update deprecated methodifisinstance(v, list):
                get_keys(v, keys_list)
            elifisinstance(v, dict):
                get_keys(v, keys_list)
            keys_list.append(k)   
    elifisinstance(d_or_l, list):
        for i in d_or_l:
            ifisinstance(i, list):
                get_keys(i, keys_list)
            elifisinstance(i, dict):
                get_keys(i, keys_list)
    else:
        print(f'** Skipping item of type: {type(d_or_l)}')  #  Altered line to use f-stringsreturn keys_list


unique_keys = list(set(get_keys(my_json_dict, keys_list)))  # Added line as example use case

Solution 4:

Here is a simple solution:

def get_nested_keys(d, keys):
    for k, v in d.items():
        if isinstance(v, dict):
            get_nested_keys(v, keys)
        else:
            keys.append(k)

keys_list = []
get_nested_keys(test_listing, keys_list)
print(keys_list)

If you want to know the hierarchy of the keys as well, you can modify the function like so:

defget_nested_keys(d, keys, prefix):
    for k, v in d.items():
        ifisinstance(v, dict):
            get_nested_keys(v, keys, f'{prefix}:{k}')
        else:
            keys.append(f'{prefix}:{k}')

Post a Comment for "Get A List Of All Keys In Nested Dictionary"