views:

149

answers:

2

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.

+7  A: 

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
Armin Ronacher
Adding runtime in Big O notation would be even better :)
Swati
M = sum(len(key.split('/')) for key in d); # Runtime is O(M)
J.F. Sebastian
+1  A: 
def layer(dict):
  for k,v in dict:
    if '/' in k:
      del dict[k]
      subdict = dict.get(k[:k.find('/')],{})
      subdict[k[k.find('/')+1:]] = v
      layer(subdict)
Mike Elkins