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.
Python code
14 linesimport 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
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
- Use urlencode(data, doseq=True) to turn list values into repeated parameters like interests=coding&interests=hiking.
- 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
More from Dictionaries & sets
- Build a Case-Insensitive Dict with a Wrapper Class in Python medium
- Build a defaultdict histogram of categories in Python easy
- Build adjacency dict graph from edges in Python easy
- Build an OrderedDict insertion order demo in Python 3 easy
- Check Invertible Mapping for Duplicate Values in Python easy
- Compare Two Dictionaries in Python easy
Keep learning
Related tutorials and quizzes for this topic.