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"}
}
},
}
When I try to access only the keys for the key 1, I get the following:
>>> print(entry[1].keys())
dict_keys(['W', 'E', 'N', 'S', 'Q'])
But for key 2 it only returns the top key and not the nested key.
>>> print(entry[2].keys())
dict_keys(['N'])
Why is it not returning the nested key of the dictionary?
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']
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With