Dictionary from String?

Dan Stromberg drsalists at gmail.com
Sun May 8 15:00:22 EDT 2011


On Sun, May 8, 2011 at 8:20 AM, Greg Lindstrom <gslindstrom at gmail.com>wrote:

> Is it possible to create a dictionary from a string value?  Something along
> these lines (but that works):
>
> >>> mystring = "{'name':'greg','hatsize':'7 5/8'}"
> >>> mystring
> "{'name':'greg','hatsize':'7 5/8'}"
> >>> dict(mystring)
> Traceback (most recent call last):
>   File "<string>", line 1, in <fragment>
> ValueError: dictionary update sequence element #0 has length 1; 2 is
> required
> >>>
>
> I would like to return an undetermined (at call time) number of fields from
> a postgres database (only 1 record) for a given request.  My thought is that
> I could build a dictionary in the form of a string, return the string and
> then convert the string value to a dictionary.  I can do that now, but I
> have to parse the string and then build the dictionary.  Any thoughts or
> help you could provide would be appreciated.
>

Does this help any?

$ /usr/local/cpython-3.2/bin/python
Python 3.2 (r32:88445, Mar  4 2011, 22:43:54)
[GCC 4.4.5] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> my_dict = {'name':'greg','hatsize':'7 5/8'}
>>> import json
>>> my_string = json.dumps(my_dict)
>>> my_string
'{"hatsize": "7 5/8", "name": "greg"}'
>>> my_dict2 = json.loads(my_string)
>>> my_dict2
{'hatsize': '7 5/8', 'name': 'greg'}
>>> my_dict == my_dict2
True
>>>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20110508/dbd0ae04/attachment.html>


More information about the Python-list mailing list