Tranquil Oshan
Tranquil Oshan

Reputation: 308

Convert dictionary of dictionary into pandas dataframe

I have this kind of dictionary

{100: {11: 0.01,
 13: 0.21,
 15: 0.5,
 17: 0.54,
 19: 0.6},

110:{11:0.5,
13:0.6,
15:0.8,
17:0.5
}
}

I want to make to convert it something like this

MainId,Id,Value
100,11,0.01
100,13,0.21
100,15,0.5
100,17,0.54
100,19,0.6
110,11,0.5
110,13,0.6
110,15,0.8
110,17,0.5

How do it do it ? Any suggestions

Upvotes: 1

Views: 250

Answers (1)

jezrael
jezrael

Reputation: 862511

Use list comprehension for tuples with DataFrame constructor:

d = {100: {11: 0.01,
 13: 0.21,
 15: 0.5,
 17: 0.54,
 19: 0.6},

110:{11:0.5,
13:0.6,
15:0.8,
17:0.5
}
}

df = pd.DataFrame([(k, k1, v1) for k, v in d.items() for k1, v1 in v.items()],
                   columns=['MainId','Id','Values'])
print (df)
   MainId  Id  Values
0     100  11    0.01
1     100  13    0.21
2     100  15    0.50
3     100  17    0.54
4     100  19    0.60
5     110  11    0.50
6     110  13    0.60
7     110  15    0.80
8     110  17    0.50

Upvotes: 2

Related Questions