Space Python Loading Python…

Index by ID

Write the codeMedium 2 stages

The crew ask for cargo by ID all day long: "where is CG-0045, and how heavy is it?". Searching the whole manifest list for every question works for six items, but the real manifest has thousands.

Build an index from ID to record once, then answer the questions from it.

Build a dict called by_id that maps each cargo ID to its record, then look up wanted in it and print the record:

CG-0045 | CO2 scrubber cartridges | life support | 31.3 kg

Start with by_id = {} and, for each record, store it under record["id"]. Then by_id[wanted] is the whole record.

Index the manifest
A real index

Finish stage 1 to unlock this stage.

The crew send a list of requests instead of one ID. Answer each one from the index; an ID that isn't in it gets a message instead of a KeyError:

CG-0044 | Freeze-dried meals | food | 42.0 kg
CG-0099: not on the manifest
CG-0042 | Water filter cartridges | life support | 18.5 kg

Build by_id as before, then loop over requests and check each ID with in by_id before looking it up.

Answer every request
Works for any requests
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

Creating Dictionaries

creating-dictionaries-python.py
# A dictionary stores pairs: a key, then its value
webb = {
    "name": "James Webb Space Telescope",
    "mirror_metres": 6.5,
    "launched": 2021,
    "instruments": 4,
    "infrared": True,
}
print(webb)

# Square brackets look up a value by its key
print("Mirror width:", webb["mirror_metres"], "metres")

# get() returns a fallback instead of crashing on a missing key
print("Cost:", webb.get("cost", "not recorded"))

# The dict() function builds the same thing from keyword arguments
hubble = dict(name="Hubble", mirror_metres=2.4, launched=1990)
print("Hubble mirror:", hubble["mirror_metres"], "metres")

# Keys do not have to be text. Anything unchangeable works
launch_log = {
    1990: "Hubble",
    2021: "Webb",
    (2027, "planned"): "Roman",
}
print(launch_log[1990])
print("Missions logged:", len(launch_log))
print("Anything launched in 2021?", 2021 in launch_log)
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:].