1

Goal: Turn list of strings into list of dictionaries

I have the following list of strings

 info = ['{"contributors": null, "truncated": true,  "text": "hey there"}', 
         '{"contributors": null, "truncated": false, "text": "how are you"}',
         '{"contributors": 10, "truncated": false, "text": "howdy"}']

Desired output:

 desired_info = [{"contributors": null, "truncated": true,  "text": "hey there"}, 
 {"contributors": null, "truncated": false, "text": "how are you"},
 {"contributors": 10, "truncated": false, "text": "howdy"}]

Question: How do I turn list of strings into list of dictionaries?

0

2 Answers 2

5

You can use json.loads:

import json

info = ['{"contributors": null, "truncated": true,  "text": "hey there"}',
         '{"contributors": null, "truncated": false, "text": "how are you"}',
         '{"contributors": 10, "truncated": false, "text": "howdy"}']

info = [json.loads(x) for x in info]
print(info)

Output:

[{'contributors': None, 'truncated': True, 'text': 'hey there'}, {'contributors': None, 'truncated': False, 'text': 'how are you'}, {'contributors': 10, 'truncated': False, 'text': 'howdy'}]
Sign up to request clarification or add additional context in comments.

Comments

0

so if you do:

>>> x = ['{"hi": True}']
>>> y = eval(x[0])
>>> y.get("hi")
True

so theoretically

desired_info = []
for x in info:
    desired_info.append(eval(x))

should do the trick.

I'm not sure how proper it is to use eval, but I'm sure someone will fill me in if it isn't.

2 Comments

An approach like this would work if all of his values were valid Python. Unfortunately, he is not using python booleans in his input.
It's better to use ast.literal_eval if the syntactically-valid Python code is an object literal. There's no need to allow arbitrary code execution for that.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.