How to switch the nesting structure of a dictionary of dictionaries in Python

If I have the following dictionary:

dict_a = {'a': {'x': 0, 'y': 1, 'z': 2},
          'b': {'x': 3, 'y': 4, 'z': 5}}

      

What is the best way to switch the dictionary structure to:

dict_b = {'x': {'a': 0, 'b': 3},
          'y': {'a': 1, 'b': 4},
          'z': {'a': 2, 'b': 5}}

      

+3


source to share


1 answer


With standard dictionary

Considering that a dictionary is always two levels deep, you can do this with defaultdict

:

from collections import defaultdict

dict_b = defaultdict(dict)

for k,v in dict_a.items():
    for k2,v2 in v.items():
        dict_b[k2][k] = v2
      

What gives:

>>> dict_b
defaultdict(<class 'dict'>, {'x': {'a': 0, 'b': 3}, 'z': {'a': 2, 'b': 5}, 'y': {'a': 1, 'b': 4}})
>>> dict(dict_b)
{'x': {'a': 0, 'b': 3}, 'z': {'a': 2, 'b': 5}, 'y': {'a': 1, 'b': 4}}

      

defaultdict

is a subclass dict

, you can re-include the result in vanilla dict

with dict_b = dict(dict_b)

(as shown in the second query).



With pandas

You can also use pandas

for this:

from pandas import DataFrame

dict_b = DataFrame(dict_a).transpose().to_dict()
      

This gives:

>>> DataFrame(dict_a).transpose().to_dict()
{'y': {'a': 1, 'b': 4}, 'x': {'a': 0, 'b': 3}, 'z': {'a': 2, 'b': 5}}

      

+4


source







All Articles