hlouis
hlouis

Reputation: 123

trying to parse a string and convert it to nested lists

I'm new to Python and blocking on this problem:

trying to go from a string like this:
mystring = '[ [10, 20], [20,50], [ [0,400], [50, 328], [22, 32] ], 30, 12 ]'

to the nested list that is represented by the string. Basically, the reverse of str(mylist)

If I try the obvious option
list(mystring)

it separates each character into a different element and I lose the nesting.

Is there an attribute to the list or str types that does this that I missed in the doc (I use Python 3.3)? Or do I need to code a function that does this?

additionnaly, how would you go about implementing that function? I have no clue what would be required to create nested lists of arbitrary depth...

Thanks,

--Louis H.

Upvotes: 2

Views: 308

Answers (2)

Slater Victoroff
Slater Victoroff

Reputation: 21934

Alternately if you're looking to do this for a more general conversion from strings to objects I would suggest using the json module. Works with dictionaries, and returns a tried and true specification that can be readily used throughout the developer and web space.

import json
nested_list = json.reads(mystring)
# You can even go the other way
mystring == json.dumps(nested_list)
>>> True

Additionally, there are convenient methods for dealing directly with files that contain this kind of string representation:

# Instead of
data_structure = json.loads(open(filename).read())
# Just
data_structure = json.load(filename)

The same works in reverse with dump instead of load

If you want to know why you should use json instead of ast.literal_eval(), it's an extremely established point and you should read this question.

Upvotes: 2

Ramchandra Apte
Ramchandra Apte

Reputation: 4079

Call the ast.literal_eval function on the string.

To implement it by oneself, one could use a recursive function which would convert the string into a list of strings which represent lists. Then those strings would be passed to the function and so on.

If I try the obvious solution list(mystring) it separates each character into a different element and I lose the nesting.

This is because list() actually generates a list out of an iterable, which list() converts into a iterator using the __iter__() method of strings. When a string is converted into an iterator, each character is generated.

Upvotes: 4

Related Questions