Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Converting dictionary of lists of dictionaries to a dataframe

Say I have a dict defined as:

dict = {'1': [{'name': 'Hospital 0',
               'students': 5,
               'grad': 71},
                    
              {'name': 'Hospital 1',
               'students': 8,
               'grad': 74}],
        
        '2': [{'name': 'Hospital 0',
               'students': 11,
               'grad': 72}]
                    
               {'name': 'Hospital 1',
               'students': 10,
               'grad': 78}]}

Suppose I want to make a dataframe from this formatted as follows:

step name students grad
1 Hospital 0 5 71
1 Hospital 1 8 74
2 Hospital 0 11 72
2 Hospital 1 10 78

Do you guys have any ideas?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Here is an approach using json_normalize() Note: I am using data as variable name instead of dict which is python built-in function.

from pandas import json_normalize
import pandas as pd 

dfs = [json_normalize(data[key]).assign(step=key) for key in data if "name" in data[key][0]]
df = pd.concat(dfs, ignore_index=True)
df = df[["step", "name", "students", "grad"]]
print(df)

  step        name  students  grad
0    1  Hospital 0         5    71
1    1  Hospital 1         8    74
2    2  Hospital 0        11    72
3    2  Hospital 1        10    78
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading