Use it when looping over devices or interfaces, or pulling values out of API responses.
Python Data Structures
Python data structures hold structured network data: lists (ordered items), dictionaries (key/value), nested combinations of both as returned by APIs, plus tuples and sets.
1. print(type(data)) — dict or list at the top?
2. print(data.keys()) / print(data[0]) — what is inside?
3. KeyError → use .get() or check the key's spelling and case.
4. Loop: for intf in data['interfaces']: print(intf['name']).
5. Pretty-print with json.dumps(data, indent=2) to see nesting.
correct interpreter and libraries → script parses → inputs read and validated → logic runs → output or change verified
The script crashes with KeyError/TypeError or returns the wrong interface, VLAN or neighbor.
Possible stored cause: The code assumes a different nesting (list vs dictionary, optional keys) than the real API or parser output.Context & applicabilityCommon mistakes · platform/version boundaries
Operational reference
Fast context before you go deeper.
Verification & Troubleshooting
Start with the observed symptom, prove the nearest boundary, and move outward only when the current state is understood.
Use the operational verification above to establish the expected state.
The script crashes with KeyError/TypeError or returns the wrong interface, VLAN or neighbor.
Step 1 Verification & evidence Verify boundary
Inspect keys/types, iterate deterministic samples and handle absent/optional fields.
Step 2 Common failure modes Narrow the fault
Wrong nesting assumption, KeyError, list/dict confusion or mutating shared data unexpectedly.
Step 3 Troubleshooting workflow Narrow the fault
Focus for this topic: Wrong nesting assumption, KeyError, list/dict confusion or mutating shared data unexpectedly.
Step 4 Common mistakes Narrow the fault
- Accessing nested keys without checking they exist (
KeyError); use.get(). - Modifying a list while iterating over it.
- Confusing a list of dicts with a dict of lists when parsing API output.
Evidence · 1 on this Topic
Expected observations and documentation recipes are reference material. Record actual output, device identity, scope and time before claiming a verified result.
data['key'] raises KeyError if missing — use data.get('key'). API responses are usually a dict containing a list of dicts: loop with for item in data['items']:. Copy before modifying a list you are looping over. json.loads() turns JSON text into these structures.
python3 --versionandwhich python3— interpreter in use.python3 -m venv .venv && . .venv/bin/activate— isolated environment.pip list— installed libraries (requests, netmiko, ncclient, pyyaml).python3 -m py_compile script.py— syntax check.python3 -i script.py/print(type(x), x)— inspect values while debugging.
ReferenceWhat it is1 section · depth on demand
Concept overview
Lists, dictionaries, nested data and iterating structured network/API results.
Key ideas: API responses naturally map to dictionaries/lists. Correct indexing/iteration is foundational for extracting interfaces, devices and status data.
ReferenceWhy it matters1 section · depth on demand
Why it matters
API responses naturally map to dictionaries/lists. Correct indexing/iteration is foundational for extracting interfaces, devices and status data.
ReferenceImportant terms & boundaries2 sections · depth on demand
In depth
Python data structures for network data
Network data maps directly onto Python's built-in structures, and the official tutorial describes their behaviour:
- Lists: ordered and mutable, with
append,extend,insert,remove,popandsort. - Tuples: immutable.
- Sets: unordered, with no duplicates, fast membership tests and set operations.
- Dictionaries: map hashable keys to values and keep insertion order.
get()returnsNoneinstead of raisingKeyError.
Comprehensions, enumerate, zip and sorted cover most data handling.
Which structure for which data
| Data | Structure | Example |
|---|---|---|
| A device's attributes | Dictionary | {"name": "acc-2f-01", "ip": "10.255.1.21", "vlans": [110, 120]} |
| An inventory | A list of dictionaries | [dev1, dev2, ...] |
| Index by hostname | A dictionary of dictionaries | devices["acc-2f-01"]["ip"] |
| VLANs on a trunk | A set | allowed = {110, 120, 999} |
| A fixed pair (interface, VLAN) | Tuple | ("Gi1/0/14", 110), usable as a dictionary key |
Set operations for comparisons
| Question | Expression |
|---|---|
| VLANs missing on the far end | local - remote |
| VLANs on both ends | local & remote |
| Every VLAN involved | local | remote |
| Is VLAN 120 allowed? | 120 in allowed |
>>> local = {110, 120, 999}
>>> remote = {110, 999}
>>> local - remote
{120}
>>> devices = [
... {"name": "acc-2f-01", "ip": "10.255.1.21", "role": "access"},
... {"name": "dist1", "ip": "10.255.0.21", "role": "distribution"},
... ]
>>> by_name = {d["name"]: d for d in devices}
>>> by_name["dist1"]["ip"]
'10.255.0.21'
>>> by_name.get("core9")
>>> [d["name"] for d in devices if d["role"] == "access"]
['acc-2f-01']
>>> for i, d in enumerate(sorted(devices, key=lambda d: d["name"]), 1):
... print(i, d["name"])
1 acc-2f-01
2 dist1
Pitfalls (tutorial)
| Pitfall | Remedy |
|---|---|
{} creates an empty dictionary, not a set | Use set() |
| Lists can't be dictionary keys | Use tuples of strings or numbers |
d["missing"] raises KeyError | Use d.get("missing", default) |
sort() returns None | Use sorted() to get a new list |
The set comparison at the start is the same check as comparing allowed VLANs on both ends of a trunk, done in one line.
Documented example, not captured output.
Quick reference
Network data maps naturally onto Python's built-in data structures: a device is a dictionary of attributes, an inventory is a list of devices, and sets make comparisons such as "which VLANs are missing?" a one-line operation. Choosing the right structure makes scripts shorter and easier to read.
Python data structures for network data:
| Type | Example | Use |
|---|---|---|
| list | ['sw1','sw2'] | Ordered items |
| dict | {'name':'sw1','ip':'10.0.0.1'} | Key/value records |
| tuple | ('Gi1/0/1', 'up') | Fixed records |
| set | {10, 20} | Unique values, set operations |
wanted = {10, 20, 30}; present = {10, 30, 99}
print(wanted - present) # missing VLANs: {20}
print(present - wanted) # unexpected VLANs: {99}
Additional reference context Scope · expected state · examples · history · terminology Open only when you need the supporting context
Verification history & basis
When and against what this Topic was checked. Later text edits do not count as a new check.
Authoritative/upstream documentation reviewed for bounded claims in Automation and Artificial Intelligence → Python Data Structures. Documentation verification only; this is not observed lab or production Evidence.
Basis: https://www.cisco.com/c/en/us/support/ios-nx-os-software/ios-xe-17/series.html · confidence 94%Deep reference
Design & tradeoffs
ENCOR design tradeoffs
Readable data models are more valuable than clever one-line code in operational automation.