2012-12-13 134 views
2

我有一个嵌套列表,我需要转换成分层字典。不过,我有点困惑如何以一种干净的pythonic方式实现它。这是我提出的一个有点难看的示例代码。如何改进?嵌套列表到分层字典

from itertools import tee,izip 
import json 

L=[(1,2,3,4,5),(1,2,7),(2,3,5),(3,4,5,6)] 

def pairs(iterable): 
    a,b = tee(iterable) 
    b.next() 
    return izip(a,b) 

def innerfunc(pairs,d): 
    try: 
     pair   = pairs.next() 
     item, nextitem = pair   
    except StopIteration:  
     return 
    if item in d:   
     innerfunc(pairs,d[item]) 
    else:   
     d[item]= {} 
     {nextitem : innerfunc(pairs,d[item])} 


def outerfunc(matrix): 
    result_dict={} 
    for row in matrix:   
     iter_pairs = pairs(row+(0,)) 
     innerfunc(iter_pairs,result_dict) 
    return result_dict 

print json.dumps(outerfunc(L), sort_keys=True, indent=4) 

输出:

{ 
    "1": { 
     "2": { 
      "3": { 
       "4": { 
        "5": {} 
       } 
      }, 
      "7": {} 
     } 
    }, 
    "2": { 
     "3": { 
      "5": {} 
     } 
    }, 
    "3": { 
     "4": { 
      "5": { 
       "6": {} 
      } 
     } 
    } 
} 

回答

2

你可以做到这一点非常简洁地使用递归:

def append_path(root, paths): 
    if paths: 
     child = root.setdefault(paths[0], {}) 
     append_path(child, paths[1:]) 

# Example usage 
root = {} 
for p in [(1,2,3,4,5),(1,2,7),(2,3,5),(3,4,5,6)]: 
    append_path(root, p) 

# Print results 
import json 
print json.dumps(root, indent=4) 

输出:

{ 
    "1": { 
     "2": { 
      "3": { 
       "4": { 
        "5": {} 
       } 
      }, 
      "7": {} 
     } 
    }, 
    "2": { 
     "3": { 
      "5": {} 
     } 
    }, 
    "3": { 
     "4": { 
      "5": { 
       "6": {} 
      } 
     } 
    } 
} 
+0

感谢。这看起来好多了。 – root

+0

不客气@root。 –

+0

噢,并假设你使用这个来实现前缀匹配的trie,这里是我后来发布的一个片段:https://gist.github.com/736416 –