python - Reverse mapping on nested dictionary -


i have dictionary

{     'eth1': {             'r2': bw1,             'r3': bw3             },     'eth2': {             'r2': bw2,             'r3': bw4         } } 

and turn dictionary

{     'r2': {         'eth1': bw1,         'eth2': bw2,     },     'r3': {         'eth1': bw3,         'eth2': bw4     } } 

is there neat way of doing that?

you can use nested-loop go through dictionary, , construct new 1 updating key/values using setdefault.

d={     'eth1': {             'r2': 'bw1',             'r3': 'bw3'             },     'eth2': {             'r2': 'bw2',             'r3': 'bw4'         } } result = {}  k, v in d.iteritems():     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 write smaller solution, , give same result.

result = {}  res= [result.setdefault(a, {}).update({k:b}) k, v in d.iteritems() a,b in v.iteritems()] print result   #output: {'r2': {'eth2': 'bw2', 'eth1': 'bw1'}, 'r3': {'eth2': 'bw4', 'eth1': 'bw3'}} 

Comments

Popular posts from this blog

c++ - QTextObjectInterface with Qml TextEdit (QQuickTextEdit) -

javascript - angular ng-required radio button not toggling required off in firefox 33, OK in chrome -

xcode - Swift Playground - Files are not readable -