For ex, I have this string:
"[{'id': 10402, 'name': 'Music'}, {'id': 18, 'name': 'Drama'}]"
I want to convert it into an actual list with dictionaries, how can I do it?
For ex, I have this string:
"[{'id': 10402, 'name': 'Music'}, {'id': 18, 'name': 'Drama'}]"
I want to convert it into an actual list with dictionaries, how can I do it?
What you (appear to) have is a Python list literal. You can use ast.literal_eval
to parse it:
>>> from ast import literal_eval
>>> x = "[{'id': 10402, 'name': 'Music'}, {'id': 18, 'name': 'Drama'}]"
>>> literal_eval(x)
[{'id': 10402, 'name': 'Music'}, {'id': 18, 'name': 'Drama'}]
If the double quotes are actually part of your string, you can do the same, but the result will be a string literal that you would need to parse again:
>>> x = "\"[{'id': 10402, 'name': 'Music'}, {'id': 18, 'name': 'Drama'}]\""
>>> literal_eval(x)
"[{'id': 10402, 'name': 'Music'}, {'id': 18, 'name': 'Drama'}]"
>>> literal_eval(literal_eval(x))
[{'id': 10402, 'name': 'Music'}, {'id': 18, 'name': 'Drama'}]
You have a list of dictionaries encoded in a string with Python syntax:
string = "[{'id': 10402, 'name': 'Music'}, {'id': 18, 'name': 'Drama'}]"
To transform it into an actual list of dictionaries, the eval
built-in function could be used:
eval(string)
That way, the string will be parsed, and a list containing the two dictionaries will be created.
But, please, note that the eval
function is dangerous since any code can be evaluated. So it's safer to use the ast.literal_eval
function for the simple task of creating that list of dictionaries:
import ast
ast.literal_eval(string)
The reason is that the string may only consist of simple literal structures (basically a very restricted subset of Python syntax).
Keep in mind that even ast.literal_eval
is not completely safe, according to the corresponding documentation: It is possible to crash the Python interpreter with a sufficiently large/complex string due to stack depth limitations in Python’s AST compiler.