简体   繁体   中英

Iterate nested dictionary and replace all tuples with one of its elements, keeping dictionary structure

I've seen other questions about iterating nested dictionaries, but nothing quite like what I'm trying to do. Take the following nested dictionary, which may also have lists as their innermost values.

d = {(1, 2) : {(3, 4) : [(5, 6), (7, 8)]}, (9, 10) : {(11, 12) : (13, 14)}}

I want to replace every tuple with either its first element, or second element (my choice). So if I choose first element, I would get the following dictionary:

d = {1 : {3 : [5, 7]}, 9 : {11 : 13}}

And if I chose the second element, I would get

d = {2 : {4 : [6, 8]}, 10 : {12 : 14}}

Thanks.

I ended up going this route:

level1 = {(1, 2) : {(3, 4) : [(5, 6), (7, 8)]}, (9, 10) : {(11, 12) : [(13, 14)]}}

i = 0 # or i = 1
for k1, level2 in list(level1.items()):
    for k2, level3 in list(level2.items()):
        for j, value in enumerate(level3):
            level3[j] = value[i]
        level2[k2[i]] = level2.pop(k2)
    level1[k1[i]] = level1.pop(k1)

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