We're sorry but this app doesn't work properly without JavaScript enabled. Please enable it to continue.

This lesson's interactive features are locked, please to keep using them

Variable-Depth JSON

Simple JSON access is easy:

score = data["player"]["stats"]["score"]

The problem is that real API responses aren't always so predictable. Sometimes a field is nested 2 levels deep. Sometimes it's 4. Sometimes part of the path is missing entirely.

If you keep chaining .get() over and over, the code can get... unwieldy.

A Reusable Pattern

I like this helper function:

from typing import Any


def extract_nested_value(data: dict[str, Any], *keys: str) -> Any | None:
    current = data
    for key in keys:
        if not isinstance(current, dict):
            return None
        current = current.get(key)
        if current is None:
            return None
    return current

It walks through a nested dictionary one key at a time, and if any key is missing, it returns None instead of crashing. Here's the usage:

game_data = {"player": {"stats": {"score": 4500, "level": 12}}}

score = extract_nested_value(game_data, "player", "stats", "score")
# 4500
mana = extract_nested_value(game_data, "player", "stats", "mana")
# None (but no crash)

This isn't mandatory; it's just a clean way to avoid writing the same nested-access logic over and over.

What *keys Means

The *keys parameter accepts however many extra arguments are passed in and collects them into a tuple called keys. So in this call:

extract_nested_value(game_data, "player", "stats", "score")

keys is:

("player", "stats", "score")

Assignment

SnackStack's smart appliances send telemetry as nested JSON.

Complete the get_device_temperature function. It accepts a device json_string and returns the nested temperature reading, a float, if available.