0

Currently, whenever I need to parse a query string, I was originally doing

 from urllib import parse

 path = parse.urlparse(self.path)
 query = parse.parse_qs(path.query)

 value = query[name][0]

But I didn't like the [0]s dotted around my code - it felt wrong in some hard to pinpoint way, so I realised I could do

 from urllib import parse

 path = parse.urlparse(self.path)
 query = dict(parse.parse_qsl(path.query))

 value = query[name]

That has the advantage of removing the [0]'s, but it risks discarding multiple values (which should be fine for my application, which shouldn't be receiving multiple values anyway).

Is there a cleaner way of parsing urlencoded strings, that gives you a dict of minimal values: the value if there's only one value, or a list if there's multiple?

A function to do so shouldn't be too difficult, but I'm curious if there's a library that does this so I don't need to reinvent the wheel.

1 Answer 1

2

In general, if you have such a dictionary query, you could always do

query = {[(k, v[0] if len(v) == 1 else v) for k, v in query.iteritems()]}

However, I really dislike this code, as it just produces stuff that is unintuitive later on.

Sign up to request clarification or add additional context in comments.

1 Comment

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.