Dictionary from String?

python w.g.sneddon at gmail.com
Mon May 9 21:33:31 EDT 2011


On May 8, 12:43 pm, Benjamin Kaplan <benjamin.kap... at case.edu> wrote:
> On Sun, May 8, 2011 at 8:20 AM, Greg Lindstrom <gslindst... 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.
>
> > --greg
>
> building the dictionary as a string seems like a hacky thing to do and
> you might want to reevaluate your methods. But if everything in the
> dict is a literal, you can do ast.literal_eval.
>
>
>
>
>
>
>
>
>
> > --
> >http://mail.python.org/mailman/listinfo/python-list

There are lots of possibilites and the "best" solution will very based
on your strings' structure.  List of tuples convert to dict nicely for
example.  So if your string can be parse to a list of tuples.

a = [ (chr(num),num) for num in range(48,58)]
[('0', 48), ('1', 49), ('2', 50), ('3', 51), ('4', 52), ('5', 53),
('6', 54), ('7', 55), ('8', 56)]
dict(a)
{'1': 49, '0': 48, '3': 51, '2': 50, '5': 53, '4': 52, '7': 55, '6':
54, '9': 57, '8': 56}
if your string looks something like your example above. The shlex
module might be helpful.



More information about the Python-list mailing list