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}]
0

2 Answers 2

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)
Sign up to request clarification or add additional context in comments.

4 Comments

Its converting but when i try to loop through the items in the list its saying its a type of string not dictionary. i have to cast it to dictionary? if so how would i do that?
Can you give a little code sample of what you do/want to do? which loop doesn't work?
If I print type(x) for x in res, then I get <class 'dict'> as answer. Which specs are you running?
Sorry i ran a wrong code so got that error.. All good. Everything worked. Thank you
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]

2 Comments

I am getting error AttributeError: 'str' object has no attribute 'read'
If I paste the code to python it works for me. Can you give it a shot?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.