Dictionary from String?

Chris Angelico rosuav at gmail.com
Sun May 8 12:16:50 EDT 2011


On Mon, May 9, 2011 at 1: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.

The first one can be done with the eval() function, but you want to be
REALLY sure that the string is safe. But if you're building the
dictionary from a database, it would be far more efficient to build it
directly in Python and return it; I'm assuming that you're currently
building the string outside of Python, but the easiest solution (in my
opinion, based solely on the information given and potentially
hopelessly useless to your actual situation) would be to simply return
multiple values from postgres and have Python do the parsing and
building.

Alternatively, if there is a character that you can guarantee does not
exist in the content, you could do something like this:
mystring = "name=greg#hatsize=7 5/8"
dict((field.split('=',1) for field in mystring.split('#')))

I used the hash character as a separator here, but you could just as
easily use a non-printing character like \n if you can be sure it
never appears in any string value. (It's okay for an equals sign, as
long as it's not in the field name.)

Hope that's of value!

Chris Angelico



More information about the Python-list mailing list