简体   繁体   中英

Reverse mapping on nested dictionary

I have this dictionary

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

And I would like to turn it into this dictionary

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

Is there a neat way of doing that?

You can use nested-loop to go through your dictionary, and construct new one by updating key/values using 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

Output:

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

You can use nested loops in list comprehensions to write smaller solution, and it would give the same result.

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'}}

Not sure why you're getting downvoted, this isn't super easy. Honestly nested dictionaries like this are a PITA. This will work:

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'}}

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