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
?
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 \w
s 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}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With