Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rearranging levels of a nested dictionary in python

Is there a library that would help me achieve the task to rearrange the levels of a nested dictionary

Eg: From this:

{1:{"A":"i","B":"ii","C":"i"},2:{"B":"i","C":"ii"},3:{"A":"iii"}}

To this:

{"A":{1:"i",3:"iii"},"B":{1:"ii",2:"i"},"C":{1:"i",2:"ii"}}

ie first two levels on a 3 levelled dictionary swapped. So instead of 1 mapping to A and 3 mapping to A, we have A mapping to 1 and 3.

The solution should be practical for an arbitrary depth and move from one level to any other within.

like image 438
Jibbity jobby Avatar asked Oct 29 '15 22:10

Jibbity jobby


2 Answers

>>> d = {1:{"A":"i","B":"ii","C":"i"},2:{"B":"i","C":"ii"},3:{"A":"iii"}}
>>> keys = ['A','B','C']
>>> e = {key:{k:d[k][key] for k in d if key in d[k]} for key in keys}
>>> e
{'C': {1: 'i', 2: 'ii'}, 'B': {1: 'ii', 2: 'i'}, 'A': {1: 'i', 3: 'iii'}}

thank god for dict comprehension

like image 93
R Nar Avatar answered Nov 04 '22 03:11

R Nar


One way to think about this would be to consider your data as a (named) array and to take the transpose. An easy way to achieve this would be to use the data analysis package Pandas:

import pandas as pd

df = pd.DataFrame({1: {"A":"i","B":"ii","C":"i"},
                   2: {"B":"i","C":"ii"},
                   3: {"A":"iii"}})
df.transpose().to_dict()

{'A': {1: 'i', 2: nan, 3: 'iii'},
 'B': {1: 'ii', 2: 'i', 3: nan},
 'C': {1: 'i', 2: 'ii', 3: nan}}
like image 21
maxymoo Avatar answered Nov 04 '22 04:11

maxymoo