Home > Software engineering >  convert nested dictionary to dataframe with keys & values are columns
convert nested dictionary to dataframe with keys & values are columns

Time:06-03

I have a nested dictionary like this:

{('1', 'Jim'): 'Pass',
 ('2', 'Nik'): 'Fail',
 ('3', 'Anna'): 'Pass',
 ('4', 'Bob'): 'Fail',
 ('5', 'Sam'): 'Pass',
 ('6', 'Rob'): 'Fail'}

I want to convert this to a data frame like this:

DataFrame('ID':[1,2,3,4,5,6], 
'Name':[Jim, Nik, Anna, Bob, Sam, Rob], 
Result: [Pass, Fail, Pass, Fail, Pass, Fail])

Kindly help!

CodePudding user response:

Create a series from it, reset its index, and rename the columns:

df = pd.Series(your_dict).reset_index().set_axis(['ID', 'Name', 'Result'], axis=1)

Output:

>>> df
  ID  Name Result
0  1   Jim   Pass
1  2   Nik   Fail
2  3  Anna   Pass
3  4   Bob   Fail
4  5   Sam   Pass
5  6   Rob   Fail

CodePudding user response:

import pandas as pd

dct = {('1', 'Jim'): 'Pass',
       ('2', 'Nik'): 'Fail',
       ('3', 'Anna'): 'Pass',
       ('4', 'Bob'): 'Fail',
       ('5', 'Sam'): 'Pass',
       ('6', 'Rob'): 'Fail'}

df = pd.DataFrame(dct.items(), columns=['ID_Name', 'Result'])
df[['ID', 'Name']] = pd.DataFrame(df['ID_Name'].tolist(), index=df.index)
df = df[['ID', 'Name', 'Result']]
print(df)
#   ID  Name Result
# 0  1   Jim   Pass
# 1  2   Nik   Fail
# 2  3  Anna   Pass
# 3  4   Bob   Fail
# 4  5   Sam   Pass
# 5  6   Rob   Fail
  • Related