简体   繁体   中英

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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