parse query string with urllib in Python 2.4
Asked Answered
S

3

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.

Sanbenito answered 20/11, 2009 at 10:34 Comment(0)
H
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']}
Hazzard answered 20/11, 2009 at 10:39 Comment(4)
why it's a array returned? I have to use: [0] to get final string result.Barley
@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.Manxman
the qsl version is useful for this sort of construction: for key, value in cgi.parse_qsl(querystring):...Faludi
please note, parse_qs is now part of the urlparse library. cgi.parse_qs is deprecatedHypoglycemia
H
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

Hansiain answered 6/10, 2013 at 21:35 Comment(1)
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?Gensmer
P
1
import urlparse
qs = 'first=1&second=4&third=3&first=0'

print dict(urlparse.parse_qsl(qs))

OR

print urlparse.parse_qs(qs)
Pulchia answered 9/1, 2014 at 7:28 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.