Search code examples
pythonlistappendstrip

Splitting a list inside a list


I have a list of this format:

["['05-Aug-13 10:17', '05-Aug-13 10:17', '05-Aug-13 15:17']"]

I am using:

for d in date:
    print d

This produces:

['05-Aug-13 10:17', '05-Aug-13 10:17', '05-Aug-13 15:17'] 

I then try and add this to a defaultdict, so underneath the print d I write:

myDict[text].append(date)

Later, I try and iterate through this by using:

for text, date in myDict.iteritems():
    for d in date:
        print d, '\n'

But this doesn't work, just producing the format show in the first line of code in this question. The format suggests a list in a list, so I tried using:

for d in date:
    for e in d:
        myDict[text].append(e)

But this included every character of the line, as opposed to each separate date. What am I doing wrong? How can I have a defaultdict with this format

text : ['05-Aug-13 10:17', '06-Aug-13 11:17'] 

whose values can all be reached?


Solution

  • Your list contains only one element: the string representation of another list. You will have to parse it into an actual list before treating it like one:

    import ast
    
    actual_list = ast.literal_eval(your_list[0])