how to change a string into dictionary

Chris Rebert clp2 at rebertia.com
Mon Aug 9 12:13:01 CEST 2010


On Mon, Aug 9, 2010 at 2:53 AM, Shashwat Anand <anand.shashwat at gmail.com> wrote:
> On Mon, Aug 9, 2010 at 3:03 PM, aimeixu <aimeixu at amazon.com> wrote:
>> Hi,
>> I am newbie for python ,Here is my question:
>> a = "{'a':'1','b':'2'}"
>> how to change a into a dictionary ,says, a = {'a':'1','b':'2'}
>> Thanks a lot .Really need help.
>
> Parse the string and re-create the dictionary.
>>>> s = "{'a':'1','b':'2'}"
>>>> ds = {}
>>>> for i in s.strip('{}').split(','):
> ...     key, val = i.split(':')
> ...     ds[key.strip("'")] = val.strip("'")

Just for the record, that'll break if the dictionary entries have
embedded commas or colons.
eval() will handle such cases correctly and probably* run faster, but
is obviously insecure.

If you have control of both ends of the serialization process, you
might consider using the `json` or `pickle` std lib modules instead.

Cheers,
Chris
--
*Do a benchmark obviously.
http://blog.rebertia.com



More information about the Python-list mailing list