How do you URL-encode a dictionary into a query string in Python? | A1Lab@MZeeshanM to PythonEnglish • 3 days ago

How do you URL-encode a dictionary into a query string in Python?

message-square
0

Pass the dictionary to urllib.parse.urlencode(params) from Python’s built-in urllib.parse module to serialize keys and values into a percent-encoded query string ("key1=val1&key2=val2"), setting doseq=True whenever dictionary values are lists or tuples that should expand into repeated query parameters ("tag=a&tag=b").

Basic Example

from urllib.parse import urlencode

params = {
    "q": "python & pandas",
    "page": 2,
    "category": "data science/ml",
}

# 1. Recommended: Encode a standard flat dictionary into a URL query string
query_string = urlencode(params)
print(query_string)
# Output: q=python+%26+pandas&page=2&category=data+science%2Fml

full_url = f"[https://api.example.com/search](https://api.example.com/search)?{query_string}"
print(full_url)
# Output: [https://api.example.com/search?q=python+%26+pandas&page=2&category=data+science%2Fml](https://api.example.com/search?q=python+%26+pandas&page=2&category=data+science%2Fml)

# 2. Encoding multi-value parameters (lists/tuples) using `doseq=True`:
multi_params = {"tag": ["python", "api"], "limit": 10}
print(urlencode(multi_params, doseq=True))
# Output: tag=python&tag=api&limit=10

Key Details & Edge Cases

  • Space encoding (+ vs. %20 via quote_via=urllib.parse.quote):
    • By default, urlencode() uses urllib.parse.quote_plus, which encodes spaces as + ("hello world" $\rightarrow$ "hello+world"). If your target API or RFC 3986 URI builder strictly expects %20 for spaces, pass quote_via=urllib.parse.quote:
      from urllib.parse import quote, urlencode
      
      print(urlencode({"q": "hello world"}, quote_via=quote))
      # Output: q=hello%20world
      
  • Forgetting doseq=True serializes lists as literal stringified brackets (%5B...%5D):
    • Calling urlencode({"tag": ["a", "b"]}) without doseq=True turns the list into str(["a", "b"]), yielding "tag=%5B%27a%27%2C+%27b%27%5D". Always pass doseq=True when values can be sequences (list, tuple).
  • None values serialize as the literal string "None" unless filtered first:
    • urlencode({"filter": None}) outputs "filter=None". Strip None keys beforehand when building optional API parameters:
      clean_params = {k: v for k, v in params.items() if v is not None}
      query = urlencode(clean_params, doseq=True)
      
  • Appending query parameters to a URL that may already contain ? or fragments (#):
    • Rather than blindly concatenating f"{base_url}?{urlencode(params)}" (which breaks if base_url already has ?foo=1 or #section), parse and rebuild the URL safely with urlsplit() / parse_qsl() / urlunsplit():
      from urllib.parse import parse_qsl, urlencode, urlsplit, urlunsplit
      
      parts = urlsplit("[https://example.com/items?sort=asc#top](https://example.com/items?sort=asc#top)")
      merged = dict(parse_qsl(parts.query)) | {"page": 2}
      new_url = urlunsplit(parts._replace(query=urlencode(merged, doseq=True)))
      # Output: [https://example.com/items?sort=asc&page=2#top](https://example.com/items?sort=asc&page=2#top)
      
  • HTTP client libraries (requests / httpx) handle dictionary encoding automatically:
    • If you are sending the request with requests.get(url, params=params) or httpx.get(url, params=params), pass the dictionary directly to params=—do not pre-encode it with urlencode(), or the client will double-encode % signs (%20 $\rightarrow$ %2520).

Comparison of URL Query-Encoding Approaches in Python

Method Library Handles Multi-Value Lists? Space Encoding Default Best Used When
urllib.parse.urlencode(d, doseq=True) (Recommended) Built-in urllib.parse Yes (with doseq=True) + (or %20 via quote_via=quote) Building query strings for urllib.request, redirects, sign-in URLs, or custom URL builders.
requests.get(url, params=d) / httpx.get(url, params=d) requests / httpx (3rd-party) Yes (automatically) + (handled internally) Making live HTTP requests without manually constructing URL strings.
urllib.parse.quote(s, safe="") Built-in urllib.parse N/A (single string only) %20 Encoding an individual URL path segment (/users/{username}) rather than key=value query pairs.
Manual f"{k}={v}" string joining (Avoid) Built-in str Manual Unescaped (broken URLs) Never use—fails on reserved characters (&, =, ?, +, /, spaces, and non-ASCII UTF-8 text).