Tuesday, May 5, 2009

Python: parsing of header:value

Give a one line statement in python to parse a HTTP or SIP header value of the form "Header1: Value1\r\nHeader2: Value2:\r\n" by returning a tuple (('Header1', 'Value1'), ('Header2', 'Value2'). Bonus question: what are the problem in returning a dict instead?

1 comment:

Kundan said...

>>> tuple(map(lambda x: (x[0].strip(), x[1].strip()), map(lambda x: x.partition(':')[0:3:2], filter(lambda x: x != '', h.split('\r\n')))))

The problem with returning a dict is that the header ordering is lost, and multiple occurrence of same header is not handled. If these are not a constraint, then you can just return dict(...).