Home > OS >  Get values from list with dictionary
Get values from list with dictionary

Time:08-12

I have a list of dictionaries and I need to get values from it and create data frame. My list looks like below:

> list_values = [{'id': 42,
>               'start_time': 1660186432206,
>              'update_time': 1660186432235,
>               'participants': [{'object_type': 'device',
>                                'object_id': 429496764},
>                                {'object_type': 'device_2',
>                                'object_id': 429494234},
>                                {'object_type': 'device_3',
>                                'object_id': 429494123}],
>               'title':'Something'},
>               {'id': 422,
>               'start_time': 1623186432206,
>              'update_time': 1690186432235,
>               'participants': [{'object_type': 'devicedf',
>                                'object_id': 429496764},
>                                {'object_type': 'device_as',
>                                'object_id': 429494234},
>                                {'object_type': 'device_ad',
>                                'object_id': 4294657123}],
>               'title':'Something213'}]

Of course this list is bigger. So basically I need create a DF that looks like below:

id    start_time       object_id
42    1660186432206    429496764
42    1660186432206    429494234
42    1660186432206    429494123
422   1623186432206    429496764
422   1623186432206    429494234 
422   1623186432206    4294657123

I have no problem to get ID and start time by using this:

id = [a['start_time'] for a in list_values ]
start_time = [b['start_time'] for b in list_values ]

Unfortunately I can't get information about object_id and concinnated it with id and start_time to create DF. Do you have any idea how I could do it? Thanks for help

Regards Tomasz

CodePudding user response:

Try:

df = pd.DataFrame(list_values).explode("participants")
df["object_type"] = df.participants.str["object_id"]
print(df[["id", "start_time", "object_type"]])

Prints:

    id     start_time  object_type
0   42  1660186432206    429496764
0   42  1660186432206    429494234
0   42  1660186432206    429494123
1  422  1623186432206    429496764
1  422  1623186432206    429494234
1  422  1623186432206   4294657123
  • Related