Convert Dynamic-Key JSON Objects to Python Dict Types

Learn how to convert JSON objects with dynamic or unknown keys into Python dict[str, T] type annotations. Covers typed dicts, iteration, and type narrowing.

Type Annotations

Detailed Explanation

Dynamic Keys as Python Dicts

When JSON object keys are not fixed (e.g., locale codes, user IDs, metric names), they cannot be modeled as dataclass fields. Instead, they map to Python's dict type.

Example JSON

{
  "translations": {
    "en": "Hello",
    "ja": "こんにちは",
    "es": "Hola"
  },
  "scores": {
    "user_001": 95,
    "user_002": 82
  }
}

Generated Python

from dataclasses import dataclass

@dataclass
class Data:
    translations: dict[str, str]
    scores: dict[str, int]

Mixed Value Types

When values are not uniform, use a union type:

{
  "settings": {
    "theme": "dark",
    "fontSize": 14,
    "autoSave": true
  }
}
from typing import Any

@dataclass
class Config:
    settings: dict[str, Any]

For more precise typing, use a union:

from typing import Union

settings: dict[str, Union[str, int, bool]]
# Python 3.10+:
settings: dict[str, str | int | bool]

Iterating Typed Dicts

for locale, text in data.translations.items():
    print(f"{locale}: {text}")
    # mypy knows locale is str and text is str

Dict vs Dataclass Decision

  • Known, fixed keys — Use a dataclass. Each key becomes a typed field.
  • Dynamic, unknown keys — Use dict[str, T]. Keys are data-driven.
  • Mixed — Use a dataclass for fixed fields and a dict field for the dynamic portion.

Nested Dicts

# JSON: {"matrix": {"row1": {"col1": 1, "col2": 2}}}
matrix: dict[str, dict[str, int]]

Type Syntax

Python version Syntax
3.7-3.8 Dict[str, int] (from typing)
3.9+ dict[str, int] (built-in)

Use Case

You receive a translations object from a CMS where locale codes are keys and translated strings are values, and you need a dict type that permits any locale while enforcing value types.

Try It — JSON to Python Converter

Open full tool