2008-09-23 41 views
7

我有一個字典創建分層的字典,看起來像這樣:需要從平坦一個

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

,我需要得到它看起來像:

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

我要指出那裏可以並且會有多個頂級密鑰(在這種情況下是'foo')。我可能會把一些東西放在一起來得到我需要的東西,但我希望有一個更高效的解決方案。

回答

8

像這樣:

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 
+0

在大O表示法中添加運行時會更好:) – Swati 2008-09-23 18:28:26

1
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) 
0

得到這個LIB打印您的字典以更好的方式。 pprinthttps://docs.python.org/3.2/library/pprint.html