Pcornel
Browse topics
Options
Recent
Favorites
Networking · Technical reference

Python Data Structures

Direct answer

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.

When to use this

Use it when looping over devices or interfaces, or pulling values out of API responses.

First 30 seconds

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.

Operational verification

correct interpreter and libraries → script parses → inputs read and validated → logic runs → output or change verified

Failure signatureScript reads the wrong value from device JSON

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
Platform / version applicability
Cisco IOS / IOS XE
applies
Structured applicability is explicit Topic metadata; it does not infer compatibility beyond the stored rows.
At a glance

Operational reference

Fast context before you go deeper.

PlatformCisco IOS / IOS XE
Scope / prerequisiteUse it when looping over devices or interfaces, or pulling values out of API responses.
What next?3 suggested next steps
Evidence1
On this pageJump to a specific section
Operational workflow

Verification & Troubleshooting

Start with the observed symptom, prove the nearest boundary, and move outward only when the current state is understood.

4 steps Observe → verify → isolate → change minimally → repeat the original test.
ObservedRecord what the original test actually shows

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 references

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.

observation · 1
Command lookup Jump straight to Cisco syntax
Key points

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.

Key checks
  • python3 --version and which 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, pop and sort.
  • Tuples: immutable.
  • Sets: unordered, with no duplicates, fast membership tests and set operations.
  • Dictionaries: map hashable keys to values and keep insertion order. get() returns None instead of raising KeyError.

Comprehensions, enumerate, zip and sorted cover most data handling.

Which structure for which data

DataStructureExample
A device's attributesDictionary{"name": "acc-2f-01", "ip": "10.255.1.21", "vlans": [110, 120]}
An inventoryA list of dictionaries[dev1, dev2, ...]
Index by hostnameA dictionary of dictionariesdevices["acc-2f-01"]["ip"]
VLANs on a trunkA setallowed = {110, 120, 999}
A fixed pair (interface, VLAN)Tuple("Gi1/0/14", 110), usable as a dictionary key

Set operations for comparisons

QuestionExpression
VLANs missing on the far endlocal - remote
VLANs on both endslocal & remote
Every VLAN involvedlocal | 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)

PitfallRemedy
{} creates an empty dictionary, not a setUse set()
Lists can't be dictionary keysUse tuples of strings or numbers
d["missing"] raises KeyErrorUse d.get("missing", default)
sort() returns NoneUse 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.

Source basisSource attribution states what this section is based on; it is not independent proof that the current environment matches it.

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:

TypeExampleUse
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}
Source basisSource attribution states what this section is based on; it is not independent proof that the current environment matches it.
Additional reference context Scope · expected state · examples · history · terminology Open only when you need the supporting context
Technical verification history

Verification history & basis

When and against what this Topic was checked. Later text edits do not count as a new check.

2026-09-14 · vendor docCisco IOS / IOS XE Current documentation reviewed 2026-09-14

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%
Depth when you need it

Deep reference

Design & tradeoffs

ENCOR design tradeoffs

Readable data models are more valuable than clever one-line code in operational automation.

Confirmation

Confirm action

Continue?