0

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?

1
  • 1
    No, it's completely impossible. Commented Nov 13, 2014 at 19:19

2 Answers 2

1

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'}} 
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.