Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert string tuples to dict

I have malformed string:

a = '(a,1.0),(b,6.0),(c,10.0)'

I need dict:

d = {'a':1.0, 'b':6.0, 'c':10.0}

I try:

print (ast.literal_eval(a))
#ValueError: malformed node or string: <_ast.Name object at 0x000000000F67E828>

Then I try replace chars to 'string dict', it is ugly and does not work:

b = a.replace(',(','|{').replace(',',' : ')
     .replace('|',', ').replace('(','{').replace(')','}')
print (b)
{a : 1.0}, {b : 6.0}, {c : 10.0}

print (ast.literal_eval(b))
#ValueError: malformed node or string: <_ast.Name object at 0x000000000C2EA588>

What do you do? Something missing? Is possible use regex?

like image 933
jezrael Avatar asked Dec 08 '22 19:12

jezrael


1 Answers

Given the string has the above stated format, you could use regex substitution with backrefs:

import re

a = '(a,1.0),(b,6.0),(c,10.0)'
a_fix = re.sub(r'\((\w+),', r"('\1',",a)

So you look for a pattern (x, (with x a sequence of \ws and you substitute it into ('x',. The result is then:

# result
a_fix == "('a',1.0),('b',6.0),('c',10.0)"

and then parse a_fix and convert it to a dict:

result = dict(ast.literal_eval(a_fix))

The result in then:

>>> dict(ast.literal_eval(a_fix))
{'b': 6.0, 'c': 10.0, 'a': 1.0}
like image 176
Willem Van Onsem Avatar answered Jan 04 '23 23:01

Willem Van Onsem