Preserve repeated and blank query values with parse_qsl
When repeated query keys are meaningful, retain a list of pairs instead of immediately converting it to a dictionary. Set keep_blank_values=True when an explicitly empty value also matters.
Run the example
Tested on Linux with Python 3.12.14. No third-party packages or network access are needed. In one Bash session, create a temporary working directory:
demo_start="$PWD"
demo_dir="$(mktemp -d)" || exit 1
cd -- "$demo_dir" || exit 1Save as demo_query_pairs.py in that directory. Use this filename to avoid shadowing a standard-library module.
from urllib.parse import parse_qsl, urlencode
query = "tag=red&tag=blue&empty=&label=a+b&literal=%2B"
pairs = parse_qsl(query, keep_blank_values=True, max_num_fields=10)
print("Pairs:", pairs)
print("Dictionary:", dict(pairs))
print("Encoded:", urlencode(pairs))
print("Default blanks:", parse_qsl("empty=&ready=yes"))Run it:
python3 demo_query_pairs.pyCaptured output:
Pairs: [('tag', 'red'), ('tag', 'blue'), ('empty', ''), ('label', 'a b'), ('literal', '+')]
Dictionary: {'tag': 'blue', 'empty': '', 'label': 'a b', 'literal': '+'}
Encoded: tag=red&tag=blue&empty=&label=a+b&literal=%2B
Default blanks: [('ready', 'yes')]Interpret the result
The dictionary retains only the last tag value, so it cannot represent the original pair sequence. Form-style decoding turns + into a space and %2B into a literal plus sign. Re-encoding produces equivalent decoded values, not a guarantee of byte-for-byte preservation of the original query spelling. The field-count limit bounds the accepted number of fields; it does not validate your application’s keys or values. No URL is fetched in this example. Apply your own duplicate-key policy before using these pairs as settings.
See the version-specific Python reference for the API contract.
Clean up
In the same Bash session, remove the source file and then the empty working directory:
rm -- demo_query_pairs.py
cd -- "$demo_start" || exit 1
rmdir -- "$demo_dir"
unset demo_start demo_dirIf the directory is not empty, inspect its remaining contents before removing anything else.
Acknowledgements
This post was created with assistance from AI.