How to Serialize a Dictionary to a Query String in Python

Convert a Python dictionary into a URL-encoded query string using the standard library's urllib.parse.urlencode function.

Easy Python 3.9+ Aug 9, 2026 Dictionaries & sets 14 views 0 copies

Python code

14 lines
Python 3.9+
import urllib.parse

def dict_to_query_string(params):
    """Serialize a dictionary to a URL query string."""
    return urllib.parse.urlencode(params)

if __name__ == "__main__":
    data = {
        "name": "Alice Johnson",
        "age": 30,
        "city": "New York",
        "interests": ["coding", "hiking"]
    }
    print(dict_to_query_string(data))

Output

stdout
name=Alice+Johnson&age=30&city=New+York&interests=%5B%27coding%27%2C+%27hiking%27%5D

How it works

The urllib.parse.urlencode function accepts a dictionary and returns a string with key-value pairs joined by &, URL-encoding both keys and values. Spaces become +, and special characters are percent-encoded automatically. The function handles multiple values for the same key if the dictionary's values are lists or tuples, but here the list is treated as a single value. This is the standard library approach, no third-party packages needed.

Common mistakes

  • Expecting list values to be serialized as repeated keys; urlencode treats them as a single value unless doseq=True is used.
  • Forgetting to handle non-string values; urlencode converts them to strings automatically.
  • Assuming the output uses %20 for spaces instead of +.
  • Using json.dumps instead of urlencode, which produces a JSON string, not a valid query string.

Variations

  1. Use urlencode(data, doseq=True) to turn list values into repeated parameters like interests=coding&interests=hiking.
  2. Pass a list of tuples instead of a dict to preserve order and allow duplicates.

Real-world use cases

  • Building query strings for HTTP GET requests to REST APIs, ensuring parameters are properly URL-encoded.
  • Constructing analytics tracking URLs with campaign parameters passed as a dictionary.
  • Creating signed URLs with query parameters for generating shareable links or pagination tokens.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Dictionaries & sets

Related tutorials and quizzes for this topic.