Convert Dictionary to String, vice versa?
Byron
DesertLinux at netscape.net
Wed Sep 15 19:55:39 EDT 2004
Hi Kjetil,
Thank you for telling me about pickle (along with the sample of code.)
It works great... Much appreciated!
Byron
---
Kjetil Torgrim Homme wrote:
> [Byron]:
>
>> I am a newbie and would like to know if it is possible to convert
>> a string back to a dictionary?
>>
>> For example, I can convert a dictionary to a string by doing this:
>>
>> >>> names = {"Candy" : 2.95, "Popcorn" : 4.95}
>> >>> strNames = str(names)
>> >>> print strNames
>> {'Popcorn': 4.9500000000000002, 'Candy': 2.9500000000000002}
>>
>> However, is there a way to convert a string back to a dictionary?
>>
>> Any help is very much appreciated!
>
>
> I'm surprised no one has mentioned pickle.
>
>
>>>>import pickle
>>>>names = {"Candy" : 2.95, "Popcorn" : 4.95}
>>>>pickle.dumps(names)
>
> "(dp0\nS'Popcorn'\np1\nF4.9500000000000002\nsS'Candy'\np2\nF2.9500000000000002\ns."
>
>>>>pickle.loads(pickle.dumps(names))
>
> {'Popcorn': 4.9500000000000002, 'Candy': 2.9500000000000002}
>
>
More information about the Python-list
mailing list