Search code examples
pythonquery-stringstandardsurllibspecifications

Multiple values for field names in a URL query string?


Python3's urllib.parse.parse_qs oddly returns a dictionary of string, list<string> for query strings:

>>> import urllib.parse as p
>>> url = p.urlparse("http://exam.ple/path?query=string&yes=no")
ParseResult(scheme='http', netloc='exam.ple', path='/path', params='', query='query=string&yes=no', fragment='')

>>> p.parse_qs(url.query)
{'query': ['string'], 'yes': ['no']}

The function's documentation says that:

The dictionary keys are the unique query variable names and the values are lists of values for each name.

Can I take advantage of this "lists of values" capability somehow?

Neither Wikipedia, nor Stack Overflow, nor the IETF specification mention anything about "multiple" or "lists" of values for fields, and I can't find any such syntax:

>>> p.parse_qs(p.urlparse("http://exam.ple/path?query=string&yes=no/a=0").query)
{'query': ['string'], 'yes': ['no/a=0']}
>>> p.parse_qs(p.urlparse("http://exam.ple/path?query=string@yes=no").query)
{'query': ['string@yes=no']}
>>> p.parse_qs(p.urlparse("http://exam.ple/path?query=string;yes=no").query)
{'query': ['string'], 'yes': ['no']}
>>> p.parse_qs(p.urlparse("http://exam.ple/path?query=string,yes=no").query)
{'query': ['string,yes=no']}

No separator character seems to ever result in a key with a value containing more than one string. Is it possible?


Solution

  • You will get a list longer than 1 element if there is a repeated query key:

    >>> url = p.urlparse("http://exam.ple/path?query=string1&query=string2")
    >>> p.parse_qs(url.query)
    {'query': ['string1', 'string2']}