首页 > 解决方案 > 如何将 Python 多级字典转换为元组?

问题描述

我有一个多级字典,例如下面的示例,它需要以相反的顺序转换为元组,即最里面的元素应该首先用于创建元组。

{a: {b:c, d:{e:f, g:h, i:{j:['a','b']}}}}

输出应该是这样的:

[(j,['a','b']), (i,j), (g,h), (e,f), (d,e), (d,g), (d,i), (b,c), (a,b), (a,d)]

标签: pythondictionarytuples

解决方案


你去了,这将产生你想要的(也经过测试):

def create_tuple(d):    
    def create_tuple_rec(d, arr):
        for k in d:
            if type(d[k]) is not dict:
                arr.append((k, d[k]))
            else:
                for subk in d[k]:
                    arr.append((k, subk))
                create_tuple_rec(d[k], arr)
        return arr
    return create_tuple_rec(d, [])


# Running this
d = {'a': {'b':'c', 'd':{'e':'f', 'g':'h', 'i':{'j':['a','b']}}}}
print str(create_tuple(d))

# Will print:
[('a', 'b'), ('a', 'd'), ('b', 'c'), ('d', 'i'), ('d', 'e'), ('d', 'g'), ('i', 'j'), ('j', ['a', 'b']), ('e', 'f'), ('g', 'h')]

推荐阅读