How find all childrens values of a nested dictionary, fast!

Diez B. Roggisch deets at web.de
Thu Nov 4 13:21:44 EDT 2010


macm <moura.mario at gmail.com> writes:

> Hi Folks
>
> How find all childrens values of a nested dictionary, fast!

There is no faster than O(n) here. 
>
>>>> a = {'a' : {'b' :{'/' :[1,2,3,4], 'ba' :{'/' :[41,42,44]} ,'bc' :{'/':[51,52,54], 'bcd' :{'/':[68,69,66]}}},'c' :{'/' :[5,6,7,8]}}, 'ab' : {'/' :[12,13,14,15]}, 'ac' :{'/' :[21,22,23]}}
>>>> a['a']
> {'c': {'/': [5, 6, 7, 8]}, 'b': {'ba': {'/': [41, 42, 44]}, '/': [1,
> 2, 3, 4], 'bc': {'bcd': {'/': [68, 69, 66]}, '/': [51, 52, 54]}}}
>>>> a['a']['b']
> {'ba': {'/': [41, 42, 44]}, '/': [1, 2, 3, 4], 'bc': {'bcd': {'/':
> [68, 69, 66]}, '/': [51, 52, 54]}}
>>>> a['a']['b'].values()
> [{'/': [41, 42, 44]}, [1, 2, 3, 4], {'bcd': {'/': [68, 69, 66]}, '/':
> [51, 52, 54]}]
>
> Now I want find all values of key "/"
>
> Desire result is [41, 42, 44, 1, 2, 3, 4, 68, 69, 66, 51, 52, 54]

a = {'a' : {'b' :{'/' :[1,2,3,4], 'ba' :{'/' :[41,42,44]} ,'bc' :{'/':[51,52,54], 'bcd' :{'/':[68,69,66]}}},'c' :{'/' :[5,6,7,8]}}, 'ab' : {'/' :[12,13,14,15]}, 'ac' :{'/' :[21,22,23]}}


def f(d):
    if "/" in d:
        for v in d["/"]:
            yield v
    for value in d.values():
        if isinstance(value, dict):
            for v in f(value):
                yield v


print list(f(a))

But that gives me a different result:

  [5, 6, 7, 8, 1, 2, 3, 4, 41, 42, 44, 51, 52, 54, 68, 69, 66, 21, 22,
  23, 12, 13, 14, 15]

Why don't you expect e.g. 23 in your output?

Diez



More information about the Python-list mailing list