Home > Enterprise >  Iterate nested dictionary and replace all tuples with one of its elements, keeping dictionary struct
Iterate nested dictionary and replace all tuples with one of its elements, keeping dictionary struct

Time:02-20

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.

CodePudding user response:

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)
  • Related