如何将Python多层字典转换为元组?

时间:2018-11-14 11:39:59

标签: python dictionary tuples

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

{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)]

1 个答案:

答案 0 :(得分:1)

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

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')]