Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 –

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>>> 
>>> 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!

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading