Harrison Harrison - 5 months ago 8
Python Question

How to turn a string into a dict in Python

I have a string

{a:'b', c:'d',e:''}
. What would be the most convenient way to make it to a
dict {'a':'b', 'c':'d', 'e':''}
?

Thanks.

Answer

Depending on the complexity of what you're parsing, this could work:

s = "{a:'b', c:'d',e:''}"
d = dict([
    (x.split(':')[0].strip(), x.split(':')[1].strip("' "))
    for x in s.strip("{}").split(',')
])
Comments