How To Convert A List Within A String To A List
I have a dict where some of the values are lists. Unfortunately, Python thinks they are strings. The dict looks like this: dict = {'key': 'x', 'key1': '[1, 2, 3], ...'} When I pul
Solution 1:
You can use the ast
library to convert strings of code into actual python code.
ast.literal_eval(''.join(list(dict['key1'])))
e.g.
>>>import ast>>>_list = ['[', '1', ','' ', '2', ',', ' ', '3', ']']>>>ast.literal_eval(''.join(_list))
[1, 2, 3]
Update
As ast.literal_eval
is 2.6 and onward, see this post about backporting literal_eval
to 2.5
Post a Comment for "How To Convert A List Within A String To A List"