Dave Dave - 11 months ago 38
Python Question

Is there a pythonic way to process tree-structured dict keys?

I'm looking for a pythonic idiom to turn a list of keys and a value into a dict with those keys nested. For example:

dtree(["a", "b", "c"]) = 42
or
dtree("a/b/c".split(sep='/')) = 42


would return the nested dict:

{"a": {"b": {"c": 42}}}


This could be used to turn a set of values with hierarchical keys into a tree:

dtree({
"a/b/c": 10,
"a/b/d": 20,
"a/e": "foo",
"a/f": False,
"g": 30 })

would result in:

{ "a": {
"b": {
"c": 10,
"d": 20 },
"e": foo",
"f": False },
"g": 30 }


I could write some FORTRANish code to do the conversion using brute force and multiple loops and maybe
collections.defaultdict
, but it seems like a language with splits and joins and slices and comprehensions should have a primitive that turns a list of strings
["a","b","c"]
into nested dict keys
["a"]["b"]["c"]
. What is the shortest way to do this without using
eval
on a dict expression string?

Answer

I'm looking for a pythonic idiom to turn a list of keys and a value into a dict with those keys nested.

reduce(lambda v, k: {k: v}, reversed("a/b/c".split("/")), 42)

This could be used to turn a set of values with hierarchical keys into a tree

import functools

def merge_dict(trg, src):
    for k, v in src.items():
        if k in trg:
            merge_dict(trg[k], v)
        else:
            trg[k] = v

def hdict_from_dict(d):
    result = {}
    map(functools.partial(merge_dict, result), map(lambda kv: hdict(*kv), d.items()))
    return result

data = {
    "a/b/c": 10,
    "a/b/d": 20,
    "a/e": "foo",
    "a/f": False,
    "g": 30 }

print(hdict_from_dict(data))

Yes, the map function is not stateless. But I had to include functools.partial :)