Search code examples
pythonpython-3.xlistevalabstract-syntax-tree

How to I convert a string that contains a list of sets to list without changing the order of the sets?


I have a string that contains a list of sets -

'[{13,18},{14,19}]'

I want it to be like this -

['[13,18]','[14,19]']

When I use ast.literal_eval() the order of the sets gets changed -

>>> 
>>> l1='[{13,18},{14,19}]'
>>> 
>>> 
>>> ast.literal_eval(l1)
[{18, 13}, {19, 14}]
>>> 

Please suggest how can I keep the order of the elements inside the set. Thank you.


Solution

  • sets are inherently unordered ("arbitrarily ordered" is more precise), so the moment the set is parsed, the order is lost. If you can be sure none of the values contain a { or } that does not denote a set, and the desired end result is a list of lists (rather than the list of sets represented by your string) the solution is simple:

    braces_to_brackets = str.maketrans('{}', '[]')  # Done once up front
    
    mystr = '[{13,18},{14,19}]'
    fixed_str = mystr.translate(braces_to_brackets)  # Replace curly braces with square brackets
    parsed = ast.literal_eval(fixed_str)
    

    which produces a parsed of [[13, 18], [14, 19]], with the order preserved.

    Try it online!