

0 / 2 embers
0 / 3000 xp
click for more info
Complete a lesson to start your streak
click for more info
Difficulty: 8
click for more info
Not enough gems
Cost: 6 gems
1: Data Formats
incomplete
2: Parsing JSON
incomplete
3: Variable-Depth JSON
incomplete
4: Fetching JSON
incomplete
5: CSV Files
incomplete
6: CSV Type Conversion
incomplete
7: Filtering CSV Rows
incomplete
8: Writing CSV Files
incomplete
9: Appending to CSV Files
incomplete
Back
ctrl+,
Next
ctrl+.
This lesson's interactive features are locked, please to keep using them
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.
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.
*keys MeansThe *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")
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.