python dict parser

124 views
Skip to first unread message

Neal Becker

unread,
Oct 15, 2010, 2:20:19 PM10/15/10
to le...@googlegroups.com
I need to parse the printed representation of a python dict.

In my dict, the keys are strings (which will be printed with quotes), and the
values are either strings, integers, or floats. I came up with this:

from lepl import Word, Drop, AnyBut, String, Float, Integer, Separator,
Whitespace

key = String(quote="'")

spaces = ~Whitespace()[:]
_int = Integer() >> int
_flt = Float() >> float
value = String(quote="'") | _int | _flt
with Separator (spaces):
dict_el = key & Drop(':') & value
d = Drop ('{') & dict_el[1:,Drop(',')] & Drop ('}')


Any comments? Suggestions?

andrew cooke

unread,
Oct 15, 2010, 2:44:39 PM10/15/10
to le...@googlegroups.com

Nice. Only suggestions I have are to pipe dict_el to tuple and then d to
dict. Then you'll get back a real Python dict!

Here's my code with that added:

from lepl import Word, Drop, AnyBut, String, Float, Integer, \

Separator, Whitespace



key = String(quote="'")



spaces = ~Whitespace()[:]

_int = Integer() >> int

_flt = Float() >> float

value = String(quote="'") | _int | _flt



with Separator (spaces):

dict_el = key & Drop(':') & value > tuple

d = Drop ('{') & dict_el[1:,Drop(',')] & Drop ('}') > dict



print d.parse_string("{'a': 1, 'b': 2.3, 'c': 'd'}")[0]




Which prints:

{u'a': 1, u'c': u'd', u'b': 2.3}

In case it's not obvious the reason this works is that the tuple creates
(key, value) pairs and the standard dict constructor will actually accept a
list of pairs and construct a dict.

Andrew

On Fri, 15 Oct 2010 14:20:19 -0400, Neal Becker <ndbe...@gmail.com>
wrote:

Jasper St. Pierre

unread,
Oct 15, 2010, 6:00:01 PM10/15/10
to le...@googlegroups.com
Hm, could using DroppedSpaces work better than this?

> --
> You received this message because you are subscribed to the Google Groups "lepl" group.
> To post to this group, send email to le...@googlegroups.com.
> To unsubscribe from this group, send email to lepl+uns...@googlegroups.com.
> For more options, visit this group at http://groups.google.com/group/lepl?hl=en.
>
>

andrew cooke

unread,
Oct 15, 2010, 6:23:23 PM10/15/10
to le...@googlegroups.com
On Fri, 15 Oct 2010 18:00:01 -0400, "Jasper St. Pierre"
<jstp...@mecheye.net> wrote:
> Hm, could using DroppedSpaces work better than this?

It would be slightly neater and easier to understand, but by default it
doesn't match newlines (while Whitespace does) so you'd need:

with DroppedSpace(Whitespace()[:]):

(I was thinking people would want to handle newlines themselves, but I am
not sure that is the most common case in retrospect).

Andrew

Reply all
Reply to author
Forward
0 new messages