02 / COLLECTIONS AND DECISIONS · LESSON 07

Give records meaningful fields

Represent a server with a dictionary and update a field.

11 min · learn at your pace

Describe a record

A dictionary maps keys to values. A server can have a name, memory_gb, and owner instead of relying on the reader to remember which list position means what. Keys are unique. Assigning a value to an existing key replaces the earlier value.

Use server["name"] when the field must exist. A missing key raises KeyError, which is useful when required data is incomplete. Use server.get("site", "unknown") for an optional field with an explicit fallback. A fallback should reflect your policy rather than silently inventing a fact.

Keep data separate from presentation

Store memory as an integer and active state as a Boolean. Add units and human-readable wording only when you format a message. Dictionaries can hold lists or other dictionaries, but a small, consistent record is easiest to use in a report.

A dictionary preserves insertion order in modern Python, but consumers should normally read fields by key. Tests for this exercise inspect the record and its summary independently; changing the spelling of a required key changes the record’s meaning.

Try an example.py
server = {"name": "db-02", "memory_gb": 32}
server["owner"] = "Platform"
print(server.get("site", "unknown"))
YOUR TURN

Put it into practice.

Create server with name "web-01", memory_gb 16, and owner "Helpdesk". Change owner to "Platform". Save site using a default of "unknown" for the missing site key. Create summary as "web-01 | Platform | 16 GB".

See an explained solution
One way to solve it.py
server = {"name": "web-01", "memory_gb": 16, "owner": "Helpdesk"}
server["owner"] = "Platform"
site = server.get("site", "unknown")
summary = f"{server['name']} | {server['owner']} | {server['memory_gb']} GB"
print(summary)

The dictionary holds the machine-friendly fields. The summary presents those fields without replacing the numeric memory value with text.