Perl Dictionary Convert

Marc 'BlackJack' Rintsch bj_666 at gmx.net
Thu Jul 6 05:33:08 EDT 2006


In <mailman.7824.1152131388.27775.python-list at python.org>, Tom Grove
wrote:

> I have a server program that I am writing an interface to and it returns 
> data in a perl dictionary.  Is there a nice way to convert this to 
> something useful in Python?

You could write a little parser with pyparsing:

source = """\
{
  Calendar =  {
    Access =  { anyone = lr;};
    Class =  IPF.Appointment;
    Messages =  0;
    Size =  0;
    UIDNext =  1;
    UIDValidity =  287898056;
    Unseen =  0;
  };
  Contacts =  {
    Class =  IPF.Contact;
    Messages =  0;
    Size =  0;
    UIDNext =  1;
    UIDValidity =  287898056;
    Unseen =  0;
  };
}
"""

from pyparsing import alphas, alphanums, nums, Dict, Forward, Group, \
                      Literal, OneOrMore, Suppress, Word

OPEN_BRACE = Suppress('{')
CLOSE_BRACE = Suppress('}')
ASSIGN = Suppress('=')
STATEMENT_END = Suppress(';')
identifier = Word(alphas, alphanums + '.')
number = Word(nums).setParseAction(lambda s, loc, toks: int(toks[0]))
dictionary = Forward()
value = identifier | number | dictionary
item = Group(identifier + ASSIGN + value + STATEMENT_END)
dictionary << Dict(OPEN_BRACE + OneOrMore(item) + CLOSE_BRACE)

result = dictionary.parseString(source)
print result['Contacts']['Class']

Output is: IPF.Contact

Ciao,
	Marc 'BlackJack' Rintsch



More information about the Python-list mailing list