简体   繁体   English

迭代嵌套字典并用其元素之一替换所有元组,保持字典结构

[英]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)

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

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