2

i have list of items like this:

["{'Collaboration':5,'Communication':5,'Creativity':4,'Critical Thinking':4}", "{'Collaboration':5,'Communication':5,'Creativity':5,'Critical Thinking':4}"]

Each item is a dictionary string. How to convert list of string to list of dictionary out of this. I need a final result like this:

[{'Collaboration':5,'Communication':5,'Creativity':4,'Critical Thinking':4}, {'Collaboration':5,'Communication':5,'Creativity':5,'Critical Thinking':4}]
Nikesh Kedlaya
  • 652
  • 4
  • 10
  • 30

2 Answers2

3

Import ast and use literal_eval. That does the job.

import ast
lst = ["{'Collaboration':5,'Communication':5,'Creativity':4,'Critical Thinking':4}", "{'Collaboration':5,'Communication':5,'Creativity':5,'Critical Thinking':4}"]
res = [ast.literal_eval(x) for x in lst]
print(res)
Banana
  • 1,149
  • 7
  • 24
0

You should use json.loadsfor this. Your strings use single quotes for encapsulating string. For JSON you have to replace them with double quotes.

import json
l = ["{'Collaboration':5,'Communication':5,'Creativity':4,'Critical Thinking':4}", "{'Collaboration':5,'Communication':5,'Creativity':5,'Critical Thinking':4}"]
result = [json.loads(x.replace("'", '"')) for x in l]
clemens
  • 16,716
  • 11
  • 50
  • 65