I want to turn this string into a list of the dictionaries within it:
”[{‘id’: ‘x’, ‘name’: ‘y’}, {‘id’: ‘p’, ‘name’: ‘q’}]”
I have multiple columns in a pandas dataframe composed of similar strings to this. Some are only ”[]”
or ”[{‘id’: ‘x’, ‘name’: ‘y’}]”
, and others have many stringified dictionaries within them.
I have tried
import json
z = ”[{‘id’: ‘x’, ‘name’: ‘y’}, {‘id’: ‘p’, ‘name’: ‘q’}]”
list(json.loads(z[1:-1]))
And this works fine for when there is only one stringified dictionary (”[{‘id’: ‘x’, ‘name’: ‘y’}]”
) but because the dictionaries have shared keys, they cannot simply be jsonified.
Once this is done, I’ll retrieve the value from name
of each and create a list of those.
ANSWERED Thanks @Tenacious B
To turn the string into the list of the dicts:
import json
z = ”[{‘id’: ‘x’, ‘name’: ‘y’}, {‘id’: ‘p’, ‘name’: ‘q’}]”
data = json.loads(z.replace("'", ""))]) # this will be a list of dicts
Output:
[{'id': 'x', 'name': 'y'}, {'id': 'p', 'name': 'q'}]
And to apply to a pandas dataframe having a column with entries as the above, retrieving only the value from the desired key:
import json
df['col'] = df['col'].apply(lambda x: [i['name'] for i in json.loads(x.replace("'", ""))])