Home > Net >  How to I convert a string that contains a list of sets to list without changing the order of the set
How to I convert a string that contains a list of sets to list without changing the order of the set

Time:12-23

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.

CodePudding user response:

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!

CodePudding user response:

With a couple of judicious replacements you could just do this:

from ast import literal_eval

mystring = '[{13,18},{14,19}]'
mystring = mystring.replace('{', "'[").replace('}', "]'")
myval = literal_eval(mystring)
print(myval)

Output:

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