I'm doing anaysis in python. I have a response from a post request in json, and I want to extract several bits of information into a DataFrame to merge with another before doing some analysis.
The json is of the form:
json = {'type': 'abc',
'results': [{'users': [{'id': '1',
'score': 0.9},
{'id': '2',
'score': 0.2}],
'num_users': 2,
'name': 'john smith'},
{'users': [{'id': '3',
'score': 0.7}],
'num_users': 1,
'name': 'david jones'},
{'users': [{'id': '5',
'score': 0.8},
{'id': '6',
'score': 0.3}],
'num_users': 2,
'name': 'jane smith'}]}
In the above example I want to extract the name, and their associated the id's and scores:
| name | id_1 | score_1 | id_2 | score_2 |
|---|---|---|---|---|
| John Smith | 1 | 0.9 | 2 | 0.2 |
| David Jones | 3 | 0.7 | ||
| Jane Smith | 5 | 0.8 | 6 | 0.3 |
My initial plan when was to loop through and create a list of dictionaries before creating the dataframe, but when I did this I realised that the number of users and therefore scores varied having initially thought it should have 2 ids and scores per name.
scores = []
for i in range(0, len(json):
scores.append({'name':json[i]['name'],
'id_1': json[i]['users'][0]['id'],
'score_1': json[i]['users'][0]['score'],
'id_2': json[i]['users'][1]['id'],
'score_2': json[i]['users'][1]['score']})
pd.DataFrame(scores)
How do I create a dictionary with a varying length and of keys and different key names (_1, _2 etc.) depending upon the length? And will that work when the list of varying length dictionaries is passed to pd.DataFrame?
Thanks.