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

如何将Python多级字典转换为元组?,python,dictionary,tuples,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)] 这将产生您想要的(也经过测试): 到目前为止,您尝试了什么?我尝试了这里涉及的步骤,但它似乎不适合我的要求。 def creat

我有一个多级字典,下面的例子,它需要以相反的顺序转换成元组,也就是说,应该首先使用最里面的元素来创建元组

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

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


到目前为止,您尝试了什么?我尝试了这里涉及的步骤,但它似乎不适合我的要求。
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')]