Python
string formatting
dictionary
Python 3.x
programming tips

How do I format a string using a dictionary in python-3.x?

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

Formatting strings with a dictionary is a clean way to build readable text templates in Python 3.x. It separates template structure from variable data and makes formatting logic easier to maintain. The most common approaches are str.format, format_map, and f-strings with unpacked values.

Core Sections

Use Named Placeholders with str.format

Named placeholders map naturally to dictionary keys.

python
1user = {
2    "name": "Alice",
3    "notifications": 5,
4    "plan": "pro",
5}
6
7template = "Hello {name}, you have {notifications} new alerts on {plan}."
8message = template.format(**user)
9print(message)

**user unpacks dictionary items as keyword arguments. This is concise for known keys.

Use format_map for Direct Dictionary Input

format_map accepts a dictionary without unpacking, which can be useful in dynamic code paths.

python
1template = "Order {order_id} for {customer} is {status}."
2record = {"order_id": 1042, "customer": "Mina", "status": "shipped"}
3
4print(template.format_map(record))

Behavior is similar to format, but the API can be cleaner when data is already dictionary-shaped.

Handle Missing Keys Safely

A missing key raises KeyError with normal formatting. For optional fields, provide defaults with a custom mapping.

python
1class SafeDict(dict):
2    def __missing__(self, key):
3        return f"<{key}-missing>"
4
5profile = {"name": "Ravi"}
6template = "User {name} from {region}"
7
8print(template.format_map(SafeDict(profile)))

This avoids crashes while making missing data explicit.

Apply Numeric and Date Formatting

Dictionary values can use standard format specifiers for numbers and dates.

python
1from datetime import datetime
2
3data = {
4    "amount": 12500.5,
5    "ratio": 0.3478,
6    "created": datetime(2026, 3, 4, 10, 30),
7}
8
9template = "Total: {amount:,.2f} | Ratio: {ratio:.1%} | Date: {created:%Y-%m-%d}"
10print(template.format(**data))

Using specifiers in template text keeps output rules close to presentation logic.

Nested Dictionary Access Pattern

Format placeholders do not directly traverse nested dictionaries by key path. Flatten data first or use helper functions.

python
1def flatten_user(d):
2    return {
3        "name": d["user"]["name"],
4        "city": d["user"]["address"]["city"],
5    }
6
7payload = {"user": {"name": "Nora", "address": {"city": "Toronto"}}}
8template = "{name} lives in {city}."
9
10print(template.format(**flatten_user(payload)))

Explicit flattening improves readability and error handling for nested inputs.

F-Strings and Dictionaries

F-strings can also reference dictionary values directly and are useful for one-off formatting.

python
stats = {"ok": 120, "failed": 3}
print(f"Processed: {stats['ok']} | Failed: {stats['failed']}")

For reusable templates, str.format patterns remain easier to externalize and localize.

Template Validation Before Runtime

If templates are user-defined or loaded from files, validate required keys before formatting to produce clearer errors.

python
1def validate_keys(template_keys, data):
2    missing = [k for k in template_keys if k not in data]
3    if missing:
4        raise ValueError(f"Missing keys: {', '.join(missing)}")
5
6required = ["name", "notifications"]
7validate_keys(required, {"name": "Alice", "notifications": 5})

Early validation avoids runtime crashes deep inside rendering paths and simplifies support debugging.

Logging Formatted Output Safely

If templates include user input, sanitize before logging or rendering in HTML contexts. Formatting is presentation logic, not input validation.

A small validation step before rendering saves support time in production systems.

Common Pitfalls

  • Forgetting ** unpacking and passing dictionary as a single positional argument.
  • Crashing on missing keys instead of defining fallback behavior.
  • Mixing formatting rules in code and template inconsistently.
  • Assuming placeholders can access deep nested dictionary paths directly.
  • Using f-strings for templates that need reuse or translation later.

Summary

  • Named placeholders with dictionaries keep text generation maintainable.
  • format_map is convenient when data already exists as a mapping.
  • Add safe defaults for optional keys to prevent KeyError failures.
  • Use format specifiers for numeric and date output consistency.
  • Flatten nested data before applying template formatting.

Course illustration
Course illustration

All Rights Reserved.