嵌套字典的反向映射

2024-05-15 00:55:44 发布

您现在位置:Python中文网/ 问答频道 /正文

我有这本字典

{
    'eth1': {
            'R2': bw1,
            'R3': bw3
            },
    'eth2': {
            'R2': bw2,
            'R3': bw4
        }
}

我想把它变成这本字典

{
    'R2': {
        'eth1': bw1,
        'eth2': bw2,
    },
    'R3': {
        'eth1': bw3,
        'eth2': bw4
    }
}

有什么好办法吗?你知道吗


Tags: 字典eth1r2r3办法bw2eth2bw1
2条回答

不知道你为什么会被否决,这可不容易。像这样老老实实嵌套的词典是一个PITA。这将起作用:

d1 = {
    'eth1': {
            'R2': bw1,
            'R3': bw3
            },
    'eth2': {
            'R2': bw2,
            'R3': bw4
        }
}

>>> d2 = {}
>>> for k1, v1 in d1.items():
...   for k2, v2 in v1.items():
...     if k2 not in d2:
...       d2[k2] = {}
...     d2[k2][k1] = v2
... 
>>> d2
{'R2': {'eth2': 'bw2', 'eth1': 'bw1'}, 'R3': {'eth2': 'bw4', 'eth1': 'bw3'}}

您可以使用嵌套循环遍历字典,并通过使用setdefault更新键/值来构造新的字典。你知道吗

d={
    'eth1': {
            'R2': 'bw1',
            'R3': 'bw3'
            },
    'eth2': {
            'R2': 'bw2',
            'R3': 'bw4'
        }
}
result = {} 
for k, v in d.iteritems():
    for a,b in v.iteritems():
        result.setdefault(a, {}).update({k:b})
print result

输出:

{'R2': {'eth2': 'bw2', 'eth1': 'bw1'}, 'R3': {'eth2': 'bw4', 'eth1': 'bw3'}}

您可以在列表理解中使用嵌套循环来编写较小的解决方案,这样会得到相同的结果。你知道吗

result = {} 
res= [result.setdefault(a, {}).update({k:b}) for k, v in d.iteritems() for a,b in v.iteritems()]
print result 

#Output: {'R2': {'eth2': 'bw2', 'eth1': 'bw1'}, 'R3': {'eth2': 'bw4', 'eth1': 'bw3'}}

相关问题 更多 >

    热门问题