Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Need to create a layered dict from a flat one

I have a dict, that looks like this:

{
    'foo': {
        'opt1': 1,
        'opt2': 2,
        },
    'foo/bar': {
        'opt3': 3,
        'opt4': 4,
        },
    'foo/bar/baz': {
        'opt5': 5,
        'opt6': 6,
        }
    }

And I need to get it to look like:

{
    'foo': {
        'opt1': 1,
        'opt2': 2,
        'bar': {
            'opt3': 3,
            'opt4': 4,
            'baz': {
                'opt5': 5,
                'opt6': 6,
                }
            }
        }
    }

I should point out that there can and will be multiple top-level keys ('foo' in this case). I could probably throw something together to get what i need, but I was hoping that there is a solution that's more efficient.

like image 534
Jeremy Cantrell Avatar asked Sep 23 '08 18:09

Jeremy Cantrell


1 Answers

Like this:

def nest(d):
    rv = {}
    for key, value in d.iteritems():
        node = rv
        for part in key.split('/'):
            node = node.setdefault(part, {})
        node.update(value)
    return rv
like image 122
Armin Ronacher Avatar answered Sep 23 '22 13:09

Armin Ronacher