8 examples of working with dictionaries in Python – 3 practical examples you’ll use every day

If you’re learning Python and still feel a bit shaky about dictionaries, you’re not alone. Dictionaries power a huge amount of real-world Python code, from APIs to data science. In this guide, we’ll walk through clear, realistic examples of working with dictionaries in Python – 3 practical examples as the main focus, plus several supporting examples that mirror what you’ll see in production code. Instead of toy snippets that only exist in tutorials, we’ll use data that looks like user profiles, configuration files, JSON from APIs, and analytics results. Along the way, you’ll see how to create dictionaries, update them, loop through them, and combine them safely. These examples of working with dictionaries in Python are written with 2024–2025 usage in mind: think web services, pandas-style data handling, and configuration-driven apps. By the end, you should be able to read and write dictionary-heavy code without hesitation—and recognize when a dict is the right tool for the job.
Written by
Jamie
Published
Updated

Let’s skip the abstract theory and jump straight into real examples of working with dictionaries in Python. We’ll build up from simple lookups to patterns you actually see in production code.

Example 1: User profiles and nested dictionaries (core practical example)

A very common example of working with dictionaries in Python is modeling users. Think of what a typical web app stores about a user: name, email, preferences, maybe a login history. That maps almost perfectly onto a dictionary.

user = {
    "id": 101,
    "name": "Jordan Lee",
    "email": "jordan@example.com",
    "is_active": True,
    "preferences": {
        "theme": "dark",
        "language": "en-US",
        "newsletter": False,
    },
}

You can access top-level fields directly:

print(user["name"])        # Jordan Lee
print(user["is_active"])   # True

And nested data is just another dictionary lookup:

theme = user["preferences"]["theme"]
print(theme)  # dark

To avoid KeyError when keys might be missing (very common with API data), use .get() with a default:

language = user.get("preferences", {}).get("language", "en-US")
print(language)  # en-US

This pattern shows up constantly in production systems that consume JSON from external APIs. The JSON object you receive is, in Python terms, just a dictionary (possibly nested). If you work with APIs from organizations like data.gov or NOAA, you’ll parse their JSON into dictionaries and handle missing keys exactly like this.

Key ideas from this example:

  • Use dictionaries to model structured records (users, orders, configs).
  • Nest dictionaries to represent related sub-objects.
  • Use .get() to handle optional data safely.

This is one of the best examples of working with dictionaries in Python because it mirrors how real applications store user state.

Example 2: API responses and data transformation (practical example #2)

Modern Python code spends a lot of time talking to APIs. When you call a REST API and parse JSON with response.json(), you almost always get a dictionary (possibly containing lists of dictionaries).

Imagine a simplified response from a public health API giving vaccination stats per state. (Real datasets from agencies like the CDC follow a similar structure, though with many more fields.)

response = {
    "state": "CA",
    "population": 39000000,
    "vaccinated": 31000000,
    "updated_at": "2025-01-30T12:00:00Z",
}
``

You might want to compute the vaccination rate and reformat the data for logging or analytics.

```python
def summarize_vaccination(data: dict) -> dict:
    population = data.get("population")
    vaccinated = data.get("vaccinated")

    if not population:
        raise ValueError("Population is required")

    rate = vaccinated / population if vaccinated is not None else 0

    return {
        "state": data.get("state", "UNKNOWN"),
        "vaccination_rate": round(rate, 3),
        "updated_at": data.get("updated_at"),
    }

summary = summarize_vaccination(response)
print(summary)

Output:

{'state': 'CA', 'vaccination_rate': 0.795, 'updated_at': '2025-01-30T12:00:00Z'}

This is another realistic example of working with dictionaries in Python – 3 practical examples style: you read a dict, perform calculations, and return a new dict with just the fields you care about.

Some patterns worth copying:

  • Use dictionaries as flexible containers for semi-structured data.
  • Normalize raw dictionaries into “clean” dictionaries for downstream code.
  • Validate critical fields, and provide defaults for optional ones.

When people talk about “JSON-like data” in Python, these kinds of examples include exactly this kind of dictionary transformation.

Example 3: Configuration and feature flags (practical example #3)

By 2024–2025, configuration-driven apps are everywhere: feature flags, environment-based settings, and per-customer overrides. Dictionaries are a natural fit for this.

BASE_CONFIG = {
    "debug": False,
    "database": {
        "host": "db.prod.internal",
        "port": 5432,
    },
    "features": {
        "new_dashboard": False,
        "beta_search": False,
    },
}

DEV_OVERRIDES = {
    "debug": True,
    "database": {
        "host": "localhost",
    },
    "features": {
        "new_dashboard": True,
    },
}

A common task is merging base config with environment-specific overrides. Here’s a small, recursive merge that respects nested dictionaries:

def merge_dicts(base: dict, overrides: dict) -> dict:
    result = base.copy()
    for key, value in overrides.items():
        if (
            key in result
            and isinstance(result[key], dict)
            and isinstance(value, dict)
        ):
            result[key] = merge_dicts(result[key], value)
        else:
            result[key] = value
    return result

config = merge_dicts(BASE_CONFIG, DEV_OVERRIDES)
print(config)

Now config has development-specific settings layered on top of production defaults. This is one of the best examples of working with dictionaries in Python for real projects because it captures how teams manage configurations without hard-coding values everywhere.

You’ve now seen the 3 practical examples promised in the title:

  • User profiles and nested data.
  • API responses and data transformation.
  • Configuration and feature flags with merging.

The next sections expand with more targeted examples of working with dictionaries in Python that you’ll use constantly.

More real examples of working with dictionaries in Python

Counting and aggregating data (analytics-style example)

Analytics and data science code lean heavily on dictionaries for counting and grouping.

Imagine you have a list of page views by user:

views = [
    {"user_id": 1, "page": "/home"},
    {"user_id": 2, "page": "/products"},
    {"user_id": 1, "page": "/products"},
    {"user_id": 1, "page": "/home"},
]

You want to know how many views each user generated. A dictionary is perfect for this:

from collections import defaultdict

views_per_user = defaultdict(int)

for event in views:
    user_id = event["user_id"]
    views_per_user[user_id] += 1

print(dict(views_per_user))

Output:

{1: 3, 2: 1}

Here, the dictionary views_per_user acts as an accumulator. This is a classic example of working with dictionaries in Python for log analysis, metrics aggregation, or any kind of event counting.

You can extend this pattern into more advanced group-bys, similar to what tools like pandas do under the hood.

Fast lookups vs. linear search (performance-focused example)

Dictionaries give you average O(1) lookup time. That’s not just a theoretical perk; it matters in real code. Consider a list of product records:

products = [
    {"id": 101, "name": "Laptop", "price": 1200},
    {"id": 102, "name": "Monitor", "price": 300},
    {"id": 103, "name": "Keyboard", "price": 80},
]

If you frequently look up products by id, a dictionary keyed by id is far more efficient than scanning the list every time.

products_by_id = {p["id"]: p for p in products}

product = products_by_id.get(102)
print(product)

This pattern shows up in routing tables, caching layers, and any code that needs fast “ID → record” mapping. It’s a subtle but very real example of working with dictionaries in Python that can dramatically reduce response times in APIs and services.

Cleaning and normalizing data (data engineering example)

If you work with public datasets from sources like data.gov or academic repositories such as Harvard’s Dataverse, you’ll constantly normalize messy dictionaries into cleaner shapes.

Say you receive inconsistent country data:

raw_country = {
    "countryName": "United States",
    "code": "US",
    "population_millions": "331.9",
}

You might want to standardize keys and convert types:

def normalize_country(data: dict) -> dict:
    return {
        "name": data.get("countryName"),
        "iso_code": data.get("code"),
        "population": float(data.get("population_millions", 0)) * 1_000_000,
    }

country = normalize_country(raw_country)
print(country)

Output:

{'name': 'United States', 'iso_code': 'US', 'population': 331900000.0}

Again, this is an everyday example of working with dictionaries in Python in any data pipeline: map weird external keys to your own schema, and store the result as a clean dictionary.

Safer access with .get() and setdefault() (defensive coding example)

Real-world data is often incomplete. Two small dictionary methods show up all the time in 2024-era Python codebases:

1. .get() for optional keys

user = {"id": 1, "name": "Alex"}

nickname = user.get("nickname", "(no nickname)")
print(nickname)  # (no nickname)

2. setdefault() for grouping

Imagine grouping comments by post ID:

comments = [
    {"post_id": 1, "text": "Nice article"},
    {"post_id": 1, "text": "Very helpful"},
    {"post_id": 2, "text": "I disagree"},
]

by_post = {}

for comment in comments:
    post_id = comment["post_id"]
    by_post.setdefault(post_id, []).append(comment)

print(by_post)

Output:

{
  1: [
    {"post_id": 1, "text": "Nice article"},
    {"post_id": 1, "text": "Very helpful"}
  ],
  2: [
    {"post_id": 2, "text": "I disagree"}
  ]
}

This grouping pattern is one of the quiet best examples of working with dictionaries in Python: it’s short, expressive, and incredibly common in log processing, comment threads, and any “one-to-many” relationship.

Modern tips: making these examples of working with dictionaries in Python production-ready

Now that you’ve seen several concrete examples of working with dictionaries in Python – 3 practical examples at the core plus extra supporting patterns – let’s talk briefly about how people use them in 2024–2025 codebases.

Type hints for dictionaries

Static analysis tools like mypy and modern IDEs expect type hints. You can describe dictionary shapes more clearly:

from typing import TypedDict

class User(TypedDict, total=False):
    id: int
    name: str
    email: str
    is_active: bool

user: User = {"id": 1, "name": "Sam"}

This makes the earlier user-profile example safer and easier to navigate in large projects.

Converting between dicts and dataclasses

For more structured data, many teams pair dictionaries with dataclasses:

from dataclasses import dataclass

@dataclass
class Product:
    id: int
    name: str
    price: float

raw = {"id": 10, "name": "Mouse", "price": 25.0}
product = Product(**raw)
print(product)

You still consume and produce dictionaries at the edges (APIs, config files), but use typed objects internally. This hybrid approach builds on the same examples of working with dictionaries in Python you’ve already seen.

Dictionaries and JSON

Whenever you save or load JSON, you’re effectively serializing dictionaries.

import json

settings = {"theme": "dark", "font_size": 14}

## Save to JSON
with open("settings.json", "w") as f:
    json.dump(settings, f)

## Load from JSON
with open("settings.json") as f:
    loaded = json.load(f)

print(loaded)

This is how many apps persist configuration, cache API responses, or store lightweight data locally.

FAQ: common questions about examples of working with dictionaries in Python

What are some real examples of working with dictionaries in Python in everyday code?

Real examples include:

  • User profiles and authentication state.
  • API responses parsed from JSON (e.g., public datasets from data.gov or CDC APIs).
  • Configuration files and environment overrides.
  • Analytics counts like “page views per user” or “errors per endpoint.”
  • Caches that map IDs or URLs to precomputed results.

All of these mirror the examples of working with dictionaries in Python shown above.

Can you give an example of converting a list of dictionaries into a lookup table?

Yes. Suppose you have a list of students:

students = [
    {"id": 1, "name": "Ana"},
    {"id": 2, "name": "Ben"},
]

students_by_id = {s["id"]: s for s in students}

Now students_by_id[2] returns the full dictionary for Ben. This is a very common example of using dictionaries for fast lookups.

When should I use a dictionary instead of a list?

Use a dictionary when you care about mapping keys to values and need fast lookups by key. Use a list when order and position matter more than named fields. Many of the best examples of working with dictionaries in Python arise when you’re modeling records, configuration, or any “ID → data” mapping.

How do I safely access nested dictionary keys from API responses?

Chain .get() calls with defaults, like this:

country = api_response.get("location", {}).get("country", "Unknown")

This pattern protects you from KeyError if intermediate keys are missing, which is very common in real-world API examples of dictionary usage.


If you work through the examples in this article and adapt them to your own data—users, products, logs, configs—you’ll quickly get comfortable reading and writing dictionary-heavy Python code. That’s the skill that separates “I can follow a tutorial” from “I can ship production features.”

Explore More Python Code Snippets

Discover more examples and insights in this category.

View All Python Code Snippets