Unit 5 — Data Structures — Modeling Network Inventories
Lists in Depth
You have seen lists already. Now the full picture. Lists are ordered, mutable collections — you can add, remove, and reorder items.
devices = ["sw-core-01", "sw-access-01", "rtr-edge-01"]
devices.append("fw-dmz-01") # add to end
devices.remove("rtr-edge-01") # remove by value
devices.sort() # sort in place
print(devices)
# ['fw-dmz-01', 'sw-access-01', 'sw-core-01']
List comprehensions — build a filtered or transformed list in one line:
inventory = [
{"name": "sw-core-01", "type": "switch"},
{"name": "rtr-edge-01", "type": "router"},
{"name": "sw-access-01", "type": "switch"},
]
switches = [d["name"] for d in inventory if d["type"] == "switch"]
# ['sw-core-01', 'sw-access-01']
Read it as: "give me the name of every device in inventory where the type is switch."
Tuples — Fixed Records
A tuple is like a list but immutable — once created, it cannot change. Use tuples for fixed records that should not be modified: a device's serial number and MAC address, a site's geographic coordinates.
device_record = ("sw-core-01", "10.1.1.1", "FCW2045L03J")
name, ip, serial = device_record # unpack into variables
print(name)
# sw-core-01
Tuples use parentheses. Unpacking assigns all values in one line.
Sets — Unique Values Only
A set stores only unique values. Duplicate entries are automatically dropped. Use sets when you need to find unique VLANs, unique sites, or unique device types across a large inventory.
vlans = {10, 20, 10, 30, 20, 10}
print(vlans)
# {10, 20, 30}
Sets are unordered — use sorted() if you need a consistent output order:
print(sorted(vlans))
# [10, 20, 30]
Dictionaries — Device Records
A dictionary maps keys to values. This is how you represent a full device record — hostname maps to IP, IP maps to status, attribute maps to value.
device = {
"name": "sw-core-01",
"ip": "10.1.1.1",
"device_type": "switch",
"site": "HQ",
"vlan": 10,
}
print(device["name"]) # sw-core-01
print(device["vlan"]) # 10
Think of a dictionary like a network device's config — each attribute has a key you can look up by name.
Looping Techniques
Loop through a dictionary with .items():
for key, value in device.items():
print(f"{key}: {value}")
Loop with an index using enumerate():
for i, name in enumerate(["sw-core-01", "sw-access-01"], start=1):
print(f"{i}. {name}")
Output:
1. sw-core-01
2. sw-access-01
Loop through two lists together with zip():
hostnames = ["sw-core-01", "sw-access-01"]
ips = ["10.1.1.1", "10.1.1.2"]
for name, ip in zip(hostnames, ips):
print(f"{name} — {ip}")
Summary
- Lists: ordered, mutable — use for device inventories you need to modify
- List comprehensions: filter or transform a list in one line
- Tuples: ordered, immutable — use for fixed records like serial numbers
- Sets: unordered, unique — use to find unique VLANs or sites
- Dictionaries: key-value pairs — use to model full device records
.items(),enumerate(),zip()— tools for looping with more context