Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #4960 > unrolled thread

Re: Dictionary from String?

Started byChris Angelico <rosuav@gmail.com>
First post2011-05-09 02:16 +1000
Last post2011-05-09 02:16 +1000
Articles 1 — 1 participant

Back to article view | Back to comp.lang.python

This discussion starts older than the indexed window; earlier articles aren't shown. The article labeled Started by below is the oldest one visible, not the original post.


Contents

  Re: Dictionary from String? Chris Angelico <rosuav@gmail.com> - 2011-05-09 02:16 +1000

#4960 — Re: Dictionary from String?

FromChris Angelico <rosuav@gmail.com>
Date2011-05-09 02:16 +1000
SubjectRe: Dictionary from String?
Message-ID<mailman.1310.1304871414.9059.python-list@python.org>
On Mon, May 9, 2011 at 1:20 AM, Greg Lindstrom <gslindstrom@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

[toc] | [standalone]


Back to top | Article view | comp.lang.python


csiph-web