Reputation: 153
val = "{t:30, f:50}"
is a string value and i need to convert it into dictionary other than the conventional method of using val.split(',') and then remove brackets and take out key and bind value to it and convert it in dictionary. Can anyone suggest any better approach towards it. PLz do care that even there is no quotes in strings in keys(t and s). Got some values from db.Already tried json loads or dumps.
Upvotes: 2
Views: 49
Reputation: 4035
import re
val = "{t:30, f:50}"
t = re.search("[^{].*[^}]",val).group()
print (t)
z = t.split(",")
print (z)
mydict = {}
mydict[z[0][0]]=z[0][2]+z[0][3]
print (mydict)
>>>
t:30, f:50
['t:30', ' f:50']
{'t': '30'}
>>>
Use search()
method ofre
module
Upvotes: 1
Reputation: 67968
import re
x="{t:30, f:50}"
y=re.findall(r"([^ {,]*):([^ {,]*)[,}]",x)
print dict(y)
Try this.Simple and done in one or two steps.
Upvotes: 4