Lab 2 of 5
Β·
Semi-Guided
Handle Missing Fields in a Device Dictionary
Objective: Use try/except to catch KeyError when a required field is absent from a device record.
Instructions
Create a file called lab2.py. The device below is missing the site and vlan fields. Write a script that tries to access four fields β name, ip, site, vlan β and catches the KeyError for any missing ones, printing MISSING instead.
device = {"name": "sw-core-01", "ip": "10.1.1.1"}
fields = ["name", "ip", "site", "vlan"]
Your output must match exactly:
name: sw-core-01
ip: 10.1.1.1
site: MISSING
vlan: MISSING
Run it with python3 lab2.py. Paste your output below and submit.
π‘ Show Hint
Loop through the fields list. Inside the loop, use try/except KeyError. In the try block: print(f"{field}: {device[field]}"). In the except block: print(f"{field}: MISSING").
Paste Your Output