Space Python Loading Python…

Nested response

Write the codeEasy 2 stages

A fuller launch response from the API doesn't keep everything at the top level: the rocket is a dict of its own, and the mission holds a list of patch images. The public launch page shows the rocket and the mission patch.

Dig the two values out of the nested response, then make the page cope with a mission whose artwork isn't ready.

Print the rocket's name and the address of the first patch:

Rocket: H3
Patch: https://cdn.example.org/patches/lumen-3.png

Chain one step per level: launch["rocket"] is a dict, so launch["rocket"]["name"] is its name. The patches are a list inside the mission, and each patch is a dict.

Read the nested values
Works for any launch

Finish stage 1 to unlock this stage.

Add the operator and the orbit, and cope with a launch whose patch list is still empty:

Rocket: H3, operated by JAXA
Orbit: SSO
Patch: https://cdn.example.org/patches/lumen-3.png

With "patches": [], the last line is Patch: none. Name the parts you use more than once, rocket = launch["rocket"] and patches = launch["mission"]["patches"], and check the list before taking [0].

Show more of the launch
Works without patches
You're not logged in, so your progress is kept in this browser only. Log in to save it, and to use hints and solutions.

Hints

Nested Dictionaries

nested-dictionaries.py
# A dictionary can hold other dictionaries as its values
rockets = {
    "Falcon 9": {"origin": "USA", "debut": 2010, "payload_t": 22.8, "status": "active"},
    "Ariane 5": {"origin": "Europe", "debut": 1996, "payload_t": 20.0, "status": "active"},
    "Electron": {"origin": "New Zealand", "debut": 2017, "payload_t": 0.3, "status": "active"},
}

# One set of brackets hands you the whole inner dictionary
print(rockets["Ariane 5"])

# A second set reaches inside that inner dictionary
print("Ariane 5 payload:", rockets["Ariane 5"]["payload_t"], "tonnes")

# The same chain works for changing a value
rockets["Ariane 5"]["status"] = "retired"
print("Status is now:", rockets["Ariane 5"]["status"])

# And for adding a brand new key deep inside
rockets["Ariane 5"]["final_flight"] = 2023
print(rockets["Ariane 5"])

# get() twice over is the safe way in when you are not sure
print("Reusable?", rockets.get("Electron", {}).get("reusable", "not recorded"))

# Looping hands you the name and the entire inner dictionary
for name, facts in rockets.items():
    print(name, "flew first in", facts["debut"], "from", facts["origin"])
Open the full example
script.py
PythonLn 1, Col 1Spaces: 4
Loading the Python environment…

Separate arguments with commas. They're passed on every Run as sys.argv[1:].