python - 将列表嵌套到分层字典中

标签 python

我有一个嵌套列表,需要将其转换为分层字典。然而我有点困惑如何以干净的Python方式实现它。这是我想出的一个有点难看的示例代码。如何改进?

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": {}
            }
        }
    }
}

最佳答案

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

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": {}
            }
        }
    }
}

关于python - 将列表嵌套到分层字典中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13861532/

相关文章:

python - 使用 Python 和正则表达式在字符串中查找 C 关键字

python - ffmpeg 原始视频和音频标准输入

python - google-app-engine-django 加载装置

Python - 在使用 raw_input() 时遇到一些问题

python - OSX : Setting Enthought python path in . bash_profile 导致奇怪的终端行为

python:将行与公共(public)字段合并

python - 为什么在 pd.read_csv() 之后创建虚拟 '0' 行?

python - MatPlotLib 散点图删除

python - 枚举的直接替换,对传递的元素进行排名,这样关系就不会增加排名?

python - 将对象类型放入 Outliner Maya 中的组中