Python: how to get a list of all keys in a dictionary of dictionaries at a given depth

If I have a dictionary of dictionaries of arbitrary depth, how can I list all the keys that are in the dictionary at a given depth? or get a list of keys in the dictionary and their depth?

For example, a simple dictionary: dict_o_dicts = {'a': {1:'bob', 2: 'fred', 3: 'henry'}, 'b': {2:'fred',3: 'henry', 4: 'pascale'} }

and I need a team that does something like: print keys_at_depth(dict_o_dicts, 0) will return: ['a', 'b']

and print keys_at_depth(dict_o_dicts, 1) will return [1,2,3,4]

I can recursively go through the dictionary to find the maximum depth of the dictionary, but as soon as I try to report both the depth and the key values, I will ultimately break the recursion.

thanks

+4
source share
4 answers

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]
+1
source

, dicts

dict_o_dicts = {'a': {1:'bob', 2: 'fred', 3: 'henry'},
                'b': {2:'fred',3: 'henry', 4: 'pascale'} }
from itertools import chain
def keys_at_depth(d, l):
    if l == 0: return d.keys()
    elif l > 0: return set(chain.from_iterable([keys_at_depth(d[k], l - 1) for k in d]))

print keys_at_depth(dict_o_dicts, 1)

set([1, 2, 3, 4])
+2

dict set :

def keys_by_depth(dict_, depth=0, output=None):
    if output is None:
        output = {}
    if not depth in output:
        output[depth] = set()
    for key in dict_:
        output[depth].add(key)
        if isinstance(dict_[key], dict):
            keys_by_depth(dict_[key], depth+1, output)
    return output

:

{0: {'b', 'a'}, 1: {1, 2, 3, 4}}

Please note that this will work with mixing dictionary values ​​and not dictat every level. Only for keys with a given depth, you can call and access at a time:

>>> print(keys_by_depth(dict_o_dicts)[1])
{1, 2, 3, 4}
+2
source

It seems that you are working with a tree structure and want to get nodes with given levels. I realized that perhaps there are even more dictionaries on the same level. So the solution that I post here returns all the keys of all dictionaries at a given level.

keys=[]
def keys_at_level(tree, level):
    # TODO: Eliminate that ugly global var keys.
    if level == 0:     # Adjust this contition to your needs (0 or 1)
        # Calculate keys.
        global keys
        keys.extend(tree.keys())
    else:
        # Iter throught values and ask for dicts.
        values  =  tree.values()
        for value in values:
            if isinstance(value, dict):
                keys_at_level(value, level-1)


keys_at_level(tree, 0)
print keys
# If you don't want duplicates just do:
keys = set(keys)
0
source

All Articles