Click here to Skip to main content
15,887,477 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am trying to load a csv/excel file containing a list of lists in one of the columns. The column content is loaded as string as below example:

#this example is string

"[[['delivery_time', 'waiting_time'], ['short']], [['delivery'], ['fast']], [['delivery'], ['really'], ['great']]]"


I would like to get the following effect:

#this example is list

[[['delivery_time', 'waiting_time'], ['short']],
[['delivery'], ['fast']],
[['delivery'], ['really'], ['great']]]


Do you have a solution how to go from the first example to the second?

What I have tried:

I've tried literal_eval but it didn't help in this case.

x = ast.literal_eval(x)


I've tried some strip, split combinations but still no effect

x = [n.strip() for n in x]
Posted
Updated 14-Jun-23 2:36am
Comments
Richard Deeming 14-Jun-23 7:58am    
That almost looks like embedded JSON data - except JSON requires strings to be delimited with " instead of '.

From a brief Google, it looks like ast.literal_eval[^] should work. What output did you get when you tried it?

The easiest way to do it is the most risky. It involves dynamic execution and could result in the execution of rogue code so you would have to trust that your input strings are safe. Using your example of

Python
s = "[[['delivery_time', 'waiting_time'], ['short']], [['delivery'], ['fast']], [['delivery'], ['really'], ['great']]]"


you can convert it to a list by

Python
exec("lst = " + s)


to flatten that to a three element (in this example) you could do

Python
lst3 = []
for item in lst:
    lst3.append(item)
 
Share this answer
 
Comments
Andre Oosthuizen 14-Jun-23 10:51am    
Great to see you back here Reverend Jim!
Reverend Jim 14-Jun-23 11:30am    
Thanks. I'm a little rusty so I was glad to see a slow pitch right over the plate.
Little update here. Thank you for your response. I used ast.literal_eval(). Previously when I tried to use it I had a string without '' " so it failed. Stupid pitfalls :)
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900