Python:将dicts(树)的字典放入列表中

时间:2016-11-11 20:35:20

标签: python list dictionary tree

我有一个代表树的词典:

...
>>> from collections import Counter
>>> Counter(data)
Counter({1.0: 106, 0.0: 72, 2.0: 40, 3.0: 21, 5.0: 10, 4.0: 9, 7.0: 3, 10.0: 3, 6.0: 2, 8.0: 2, 9.0: 2, 17.0: 2, 11.0: 1, 15.0: 1, 19.0: 1, 6.09: 1, 27.0: 1})

如何将其转换为从根到叶子的所有可能路径?

输出应该是这样的:

{1: {2: 3, 4: 5}, 6: {7: 8, 9: 10}}

是否有某种Python dict理解moneliner可以解决任何字典深度的问题?

1 个答案:

答案 0 :(得分:6)

这就是递归非常适合:

def paths(tree):
    if not isinstance(tree, dict):
        return [[tree]]
    return [[key] + path
            for key, value in tree.items()
            for path in paths(value)]

print(paths({1: {2: 3, 4: 5}, 6: {7: 8, 9: {10: 11, 12: 13}}}))

输出:

[[1, 2, 3], [1, 4, 5], [6, 9, 10, 11], [6, 9, 12, 13], [6, 7, 8]]