How to Parse Query String to Dict with Duplicate Keys in Python

Convert a URL query string into a Python dictionary, merging duplicate keys into lists while keeping single values as scalars.

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

Python code

12 lines
Python 3.9+
from urllib.parse import parse_qs


def parse_query_to_dict(query_string):
    parsed = parse_qs(query_string, keep_blank_values=True)
    return {key: values if len(values) > 1 else values[0] for key, values in parsed.items()}


if __name__ == "__main__":
    query = "name=John&name=Jane&age=30&city=&city=Paris&empty_prop="
    result = parse_query_to_dict(query)
    print(result)

Output

stdout
{'name': ['John', 'Jane'], 'age': '30', 'city': ['', 'Paris'], 'empty_prop': ''}

How it works

The parse_qs function from urllib.parse splits a query string into key-value pairs, automatically handling URL decoding and duplicate keys by grouping values into lists. The dictionary comprehension then converts single-element lists back to plain values while keeping multi-element lists intact. keep_blank_values=True ensures empty values like city= and empty_prop= are preserved in the output. This approach keeps the result compact for common single-value parameters while explicitly showing duplicates.

Common mistakes

  • Forgetting `keep_blank_values=True` drops empty parameters like `city=`
  • Assuming duplicate keys are lost; always remember parse_qs groups them into lists
  • Overlooking that all values are lists by default, requiring conversion logic
  • Not URL-decoding values, though parse_qs handles percent-encoding automatically

Variations

  1. Use `urllib.parse.parse_qsl` and manually group with a defaultdict for custom merge rules
  2. Return flat lists for all keys: `{k: v for k, v in parse_qs(q).items()}` if uniform handling is preferred

Real-world use cases

  • Parsing multi-value form submissions like checkboxes or multi-select filters in a web framework.
  • Extracting repeated query parameters in API request handling where users may pass the same filter twice.
  • Normalizing incoming webhook URLs for analytic tracking where campaign tags can appear more than once.

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.