Python: How do I get a list of all keys in a dictionary of dictionaries, at a given depth
python
Solution
Recursive approach:
def key_at_depth(dct, dpt):
if dpt > 0:
return [
key
for subdct in dct.itervalues()
for key in key_at_depth(subdct, dpt - 1)
]
else:
return dct.keys()
dict_o_dicts = {
'a': {1: 'bob', 2: 'fred', 3: 'henry'},
'b': {2: 'fred', 3: 'henry', 4: 'pascale'},
}
key_at_depth(dict_o_dicts, 0)
Out[69]: ['a', 'b']
key_at_depth(dict_o_dicts, 1)
Out[70]: [1, 2, 3, 2, 3, 4]
Problem
If I have a dictionary of dictionaries, of arbitrary depth, how could I list all of the keys that are in the dictionary, at a given depth? or get a list of the keys in the dictionary and their depths? For example, a simple dictionary would be: ``` dict_o_dicts = {'a': {1:'bob', 2: 'fred', 3: 'henry'}, 'b': {2:'fred',3: 'henry', 4: 'pascale'} } ``` and I'd like a command that does something along the lines of: `print keys_at_depth(dict_o_dicts, 0)` would return: `['a', 'b']` and `print keys_at_depth(dict_o_dicts, 1)` would return `[1,2,3,4]` I can recursively walk the dictionary to find the maximum depth of the dictionary, but as soon as I try and report both the depth and the key values I end up breaking the recursion. Thanks