12

Using Python2.4.5 (don't ask!) I want to parse a query string and get a dict in return. Do I have to do it "manually" like follows?

>>> qs = 'first=1&second=4&third=3'
>>> d = dict([x.split("=") for x in qs.split("&")])
>>> d
{'second': '4', 'third': '3', 'first': '1'}

Didn't find any useful method in urlparse.

3 Answers 3

23

You have two options:

>>> cgi.parse_qs(qs)
{'second': ['4'], 'third': ['3'], 'first': ['1']}

or

>>> cgi.parse_qsl(qs)
[('first', '1'), ('second', '4'), ('third', '3')]

The values in the dict returned by cgi.parse_qs() are lists rather than strings, in order to handle the case when the same parameter is specified several times:

>>> qs = 'tags=python&tags=programming'
>>> cgi.parse_qs(qs)
{'tags': ['python', 'programming']}
Sign up to request clarification or add additional context in comments.

4 Comments

why it's a array returned? I have to use: [0] to get final string result.
@Bin Chen: Your question is a little unclear, but if you're asking why the values in the dict returned by cgi.parse_qs() are lists instead of strings, the answer is that the same parameter could be specified several times, in which case multiple values have to be returned. This is illustrated by the last example in my answer.
the qsl version is useful for this sort of construction: for key, value in cgi.parse_qsl(querystring):...
please note, parse_qs is now part of the urlparse library. cgi.parse_qs is deprecated
9

this solves the annoyance:

d = dict(urlparse.parse_qsl( qs ) )

personally i would expect there two be a built in wrapper in urlparse. in most cases i wouldn't mind to discards the redundant parameter if such exist

1 Comment

parse_qsl was added in 2.6, at which point there is parse_qs which already returns a dict. Is that what you meant by a built-in?
1
import urlparse
qs = 'first=1&second=4&third=3&first=0'

print dict(urlparse.parse_qsl(qs))

OR

print urlparse.parse_qs(qs)

Comments

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.