On Sep 5, 2010, at 1:09 PM, Roy Smith wrote:

I'm using httplib, and want to get the Location header from the
response.  The getheaders() method gives you back a list of (name,
value) tuples. It would be a lot more convenient if it gave you back a
dict, but it is what it is.

Anyway, I came up with:

   location = [t[1] for t in headers if t[0] == 'location'][0]

which works, but is getting on towards the cryptic end of things.  Is
there a better idiom for this?

Are you concerned about efficiency? If it's not important, being less terse would make it less cryptic:
location = None
for name, value in headers:
   if name == "location":
      location = value
      break

If you prefer terse, IMHO this is less cryptic (but untested):

location = [value for name, value in headers if name == 'location'] [0]


Be careful if you decide to turn the list of tuples into a dictionary. HTTP headers can repeat and straightforward code to turn the (name, value) pairs into a dict could end up overwriting data.

Cheers
P
--
http://mail.python.org/mailman/listinfo/python-list

Reply via email to