Reference library

Dictionaries & sets

Key–value maps, uniqueness, counting, grouping, and fast lookups.

2 matches
Dictionaries & sets easy

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.

query-string dict url-parsing
Python
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…
13 0 Open
Dictionaries & sets easy

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.

urllib query-string urlencode
Python
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"]
   …
13 0 Open

Browse by section

Each section groups closely related Python snippets.

Dictionaries & sets — Python code examples

What you will find here

This page collects dictionaries & sets snippets — short, copy-ready Python you can paste into our free online IDE and run without installing anything. Each sample includes a plain-English explanation and the full source code.

Samples vs tutorials and challenges

Samples are quick reference — one concept per page. For step-by-step teaching, use our Python tutorials. To test yourself, try quizzes or coding challenges. Clean up style with the Python formatter.