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

Convert Dataframe from a dictionary list

I have a dictionary list:

orderlist = [
                {
                'order_id': 5,
                'status': 'completed',
                'line_items': [{'product_id': 6,'name': 'headphone'} , {'product_id': 7,'name': 'airbuds'} ]
                },

                {
                'order_id': 6,
                'status': 'pending',
                'line_items': [{'product_id': 8,'name': 'smartwatch'} , {'product_id': 9,'name': 'smartphone'} ]
                },

            ]

and I want this dataframe:

order_id        status      product_id          name 
    5          completed        6               headphone
    5          completed        7               airbuds
    6          pending          8               smartwatch
    6          pending          9               smartphone

I have tried it like this:

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

df_order = pd.DataFrame(orderlist)

The problem is that I didn’t get my desired dataframe.

>Solution :

You can use pd.json_normalize:

df = pd.json_normalize(orderlist, ['line_items'], ['order_id', 'status'])
print(df)

Output:

   product_id        name order_id     status
0           6   headphone        5  completed
1           7     airbuds        5  completed
2           8  smartwatch        6    pending
3           9  smartphone        6    pending
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