Reference library

Dictionaries & sets

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

3 matches
Dictionaries & sets easy

How to Pickle a Python Dict and Load It Back

Save a dictionary to a binary file with pickle.dump() and reload it with pickle.load(), showing the round trip and type preservation.

pickle serialization dict
Python
import pickle

data = {"name": "Alice", "scores": [87, 92, 95], "active": True}

print("Original dict:", data)

with open("safe_demo.pkl", "wb") as f:
    pickle.dump(data, f)

with open("safe_demo.pkl", "rb") as f:
    loaded = pickle.load(f)

print("Loaded dict:", loaded)
print("Type:", type(loaded).__name__)
print(…
15 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
Dictionaries & sets easy

Serialize Python dict to JSON with custom default for datetime

Convert a Python dict containing datetime and set objects into JSON by providing a custom default serializer.

json datetime serialization
Python
import json
from datetime import datetime

def custom_serializer(obj):
    if isinstance(obj, datetime):
        return obj.isoformat()
    if isinstance(obj, set):
        return list(obj)
    return str(obj)

data = {
    "name": "Alice",
    "created_at": datetime(2024, 3, 15, 10, 30, 45),
    "tags": {"python", "j…
15 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.