Skip to content Skip to sidebar Skip to footer

Accessing Nested Keys In Python

I have a nested dictionary as below entry = { 0: {'Q': 0}, 1: {'W': 2, 'E': 3, 'N': 5, 'S': 4, 'Q': 0}, 2: { 'N': { 'Q': {'E'} } }, }

Solution 1:

keys()doesn't work that way.

keys()

Return a new view of the dictionary’s keys

Your nested dictionnary is a completely separate dict, and you can get its own keys with its own keys() method :

entry[2]['N'].keys()

If you want to recursively get all the keys inside nested dictionnaries, you will have to implement a method for that :

entry = {0: {"Q": 0},
         1: {"W": 2, "E": 3, "N": 5, "S": 4, "Q": 0},
         2: {"N": { "Q":{"E"}}},
}


def rec_keys(dictio):
    keys = []
    for (key,value) in dictio.items():
        if isinstance(value, dict):
            keys.extend(rec_keys(value))
        else:
            keys.append(key)
    return keys

print(rec_keys(entry))
# ['Q', 'Q', 'W', 'N', 'S', 'E', 'Q']

Solution 2:

When you run print(entry[2].keys())

you're asking python "What keys exist in the data corresponding to key '2'? (which in your case is another dictionary)" The answer to which is just 'N'. This is because

entry[2]

is

{"N":{"Q":{"E"}}

which has the single key 'N' and the data '{"Q":{"E"}}'

Solution 3:

dict.keys only returns the top level keys of the dictionary. If you want to get all nested keys of a dictionary, you will need to define your own function.

# interface for dictionary-like objects
from collections.abc import Mapping

def nested_keys(d) ->set:
    """
    Return a set containing all nested keys.
    """
    # If it isnot a dict-like object, return an emptyset
    if not isinstance(d, Mapping):
        returnset()

    keys = d.keys()
    for v in d.values():
        # Update the keys setwith the keys ineachvaluebyusing the union (or) operator: |
        keys |= nested_keys(v)

    return keys

Solution 4:

if you wanted to check all nested keys, you could create a loop function that checks the type of your looked up data and iterates over it if it is another dictionary, like

defprint_nested_keys(d):
    for k in d.keys():
        print(k)
        iftype(d[k]) == dict:
            print('nested dict detected - recursing...')
            print_nested_keys(d[k])

here, whenever one of the keys in your dictionary points to another dictionary, you call the function recursively to read through the lower-level dictionary keys. of course, you could always append the keys that you find in a list to return by your function in the end, if you want such a list.

Solution 5:

For only keys, Use simple recorsive function:

defrecursive_items(dict_name):
    for key, value in a.items():
        iftype(value) isdict:
            yield (key)
            yieldfrom recursive_items(value)

# print the keys for key in recursive_items(a):
   print(key)

This function will benefit for any nested dictionary

Post a Comment for "Accessing Nested Keys In Python"