Reputation: 31
I have a nested list stored in string format, that I want to convert it to python list
ll ='[["ABC",7,"A",9],["ABD",6,"B",8]]'
ll = list(ll)
print(ll)
My expected output
[["ABC",7,"A",9],["ABD",6,"B",8]]
Received output
['[', '[', '"', 'A', 'B', 'C', '"', ',', '7', ',', '"', 'A', '"', ',', '9', ']', ',', '[', '"', 'A', 'B', 'D', '"', ',', '6', ',', '"', 'B', '"', ',', '8', ']', ']']
please help
Upvotes: 3
Views: 1261
Reputation: 1896
Explanation of Error:
When you do list(ll)
, python is expected to convert the given input tuple/set/iterator into list.
In your case, ll
is a string which is internally a list of characters. So, when you apply list(ll)
, Python is returning you a list of charecters.
Recommendation
As answered by @Zalak Bhalani, I would recommend json.loads
.
import json
ll ='[["ABC",7,"A",9],["ABD",6,"B",8]]'
ll = json.loads(ll)
print(ll)
Upvotes: 2
Reputation: 1144
You can use json
.
import json
ll='[["ABC",7,"A",9],["ABD",6,"B",8]]'
ll = json.loads(ll)
print(ll)
Upvotes: 2
Reputation: 6234
You can use ast.literal_eval
to Safely evaluate an expression node or a string containing a Python literal or container display.
Note: The string or node provided may only consist of the following Python literal structures: strings, bytes, numbers, tuples, lists, dicts, sets, booleans, and None.
import ast
ll='[["ABC",7,"A",9],["ABD",6,"B",8]]'
ll = ast.literal_eval(ll)
Output:
[['ABC', 7, 'A', 9], ['ABD', 6, 'B', 8]]
Upvotes: 6
Reputation: 5889
You can use ast.literal_eval
import ast
x =ast.literal_eval('[["ABC",7,"A",9],["ABD",6,"B",8]]')
print(type(x))
print(x)
output
<class 'list'>
[['ABC', 7, 'A', 9], ['ABD', 6, 'B', 8]]
Upvotes: 1