Python online course

Lists and dictionaries

Store ordered values and look up records by key.

Lists keep items in order. Dictionaries look up a value by a key. Most admin scripts are a mix of the two: a list of hosts, each host a dictionary of facts.

hosts = ["edge-1", "edge-2"]
hosts.append("core-1")

iface = {"name": "Gi0/1", "speed": 1000, "up": True}
print(iface["name"])

Index a list with hosts[0]. Slice with hosts[1:]. A missing dictionary key raises KeyError — use iface.get("mtu", 1500) when a field might be absent.

Loop both

for name in hosts:
    print(name)

for key, value in iface.items():
    print(key, value)