Harrison Harrison - 1 year ago 80
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':''}


Answer Source

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(',')
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download