简体   繁体   English

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

[英]How to convert a Python multilevel dictionary into tuples?

I have a multi level dictionary, example below, which needs to be converted into tuples in reverse order ie, the innermost elements should be used to create tuple first.我有一个多级字典,下面的例子,它需要以相反的顺序转换成元组,即最里面的元素应该首先用于创建元组。

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

Output should be something like this:输出应该是这样的:

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

There you go, this will produce what you want (also tested):你去吧,这将产生你想要的(也经过测试):

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM