How to create a pivot nested dictionary in python

Possible duplicate:
Pythonic Path to reverse nested dictionaries

I'm having a hard time finding a solution to this nested dictionary problem. I found some itertools features that could be used, but it is not clear to me how to use them. any help on this front would be great

input = { "a" : { "x": 1, "y": 2 },
          "b" : { "x": 3, "z": 4 } }


output = {'y': {'a': 2},
          'x': {'a': 1, 'b': 3},
          'z': {'b': 4} }

      

+3


source to share


1 answer


Simplest way to use it dict.setdefault

:

i = { "a" : { "x": 1, "y": 2 },
      "b" : { "x": 3, "z": 4 } }

d = {}
for key, value in i.iteritems():    
    for ikey, ivalue in value.iteritems():
        d.setdefault(ikey,{})[key] = ivalue
print d

      



of

{'x': {'a': 1, 'b': 3}, 'y': {'a': 2}, 'z': {'b': 4}}

      

+2


source







All Articles