3

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

4 Answers 4

6

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

1 Comment

Im going to take the first post claim here by 4.0 seconds xd
2

You can use json.

import json
ll='[["ABC",7,"A",9],["ABD",6,"B",8]]'
ll = json.loads(ll)
print(ll)

Comments

2

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)

Comments

1

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

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.