Free tech learning for everyone, from basics to pro

Python for NetworkingProgramming and Application SecurityBeginner

Python data structures: lists, dictionaries, sets and tuples for networks

In short: Lists keep items in order, tuples hold fixed records, sets remove duplicates and dictionaries look values up by key. Network data such as an inventory is usually a list of dictionaries. Picking the right structure makes scripts shorter, faster and easier to read.

Why data structures matter

Almost every automation task starts with data: a list of switches, the VLANs on a trunk, the interfaces that are down. How you store that data decides how easy the rest of the script is. Python has four built-in collections, and each one fits a different job.

Python collectionsList[ ] ordered, changeableTuple( ) ordered, fixedSet{ } unique itemsDictionary{key: value} lookupList of dictsone dict per deviceDict of listssite to devices
Figure 1. The four core collections, plus two combinations you will meet constantly in network scripts.

Lists and tuples

A list is an ordered collection you can change: add, remove, sort. A tuple is ordered too, but fixed once created, which makes it a good fit for a record that should not change, such as a (hostname, IP address) pair.

switches = ["acc-sw1", "acc-sw2", "core-sw1"]
switches.append("acc-sw3")
switches.sort()
print(switches[0], len(switches))

mgmt = ("core-sw1", "192.168.10.1")
name, ip = mgmt          # unpack a tuple
print(name, ip)

Indexes start at 0, and switches[-1] gives the last item. Slicing, such as switches[0:2], returns a new list with the first two items.

Dictionaries and sets

A dictionary (dict) maps keys to values, like a lookup table. It is the natural way to describe one device or one interface. A set holds unique values only and is excellent for comparisons, such as which VLANs are allowed on one trunk but missing on the other.

device = {"hostname": "core-sw1", "ip": "192.168.10.1", "platform": "cisco_ios"}
print(device["hostname"])
print(device.get("site", "unknown"))   # default if the key is missing
device["site"] = "london"

trunk_a = {10, 20, 30, 40}
trunk_b = {10, 20, 50}
print(trunk_a - trunk_b)   # on A but not on B: {30, 40}
print(trunk_a & trunk_b)   # on both: {10, 20}

Tip: use .get() when a key may not exist. Square brackets raise a KeyError for a missing key, which is sometimes what you want and sometimes a crash.

Nesting: modelling real network data

Choosing a structureWhat do you need?pick by behaviourOrder + editslistFixed recordtupleNo duplicatessetLook up by namedict
Figure 2. Choose a collection by the behaviour you need, not by habit.

Real data is nested. An inventory is usually a list of dictionaries, one per device. This is also the shape you get when you load JSON (JavaScript Object Notation) or YAML from a file or an API, so learning it pays off everywhere.

inventory = [
    {"hostname": "acc-sw1", "ip": "192.168.10.11", "vlans": [10, 20]},
    {"hostname": "acc-sw2", "ip": "192.168.10.12", "vlans": [10, 30]},
]

for dev in inventory:
    print(dev["hostname"], dev["ip"])

all_vlans = {v for dev in inventory for v in dev["vlans"]}
print(sorted(all_vlans))

by_name = {dev["hostname"]: dev for dev in inventory}
print(by_name["acc-sw2"]["ip"])

The last two lines use comprehensions, a compact way to build a set or dict from a loop. Keep them short; if a comprehension needs a second line to explain it, write a normal loop instead.

Choosing well and common mistakes

NeedUseNetwork example
Ordered items you will changelistCommands to send, in order
A fixed recordtuple(interface, status) pairs
Unique values and comparisonssetVLANs allowed on a trunk
Look up by namedictDevice facts keyed by hostname
  • Searching a long list with in is slow; a set or dict lookup is near instant.
  • Sets have no order, so sort them before printing reports.
  • Copying with b = a does not copy a list; both names point to the same object. Use a.copy().
  • Dict keys must be unchangeable types (strings, numbers, tuples), never lists.

Practice

You need to find which VLANs exist on switch A but not on switch B. Which structure and operation fits?
Put each list of VLANs into a set and use the difference operator: set_a - set_b.
What does device.get("site", "unknown") return if the key is missing?
The default value "unknown", instead of raising a KeyError.
Why is an inventory usually stored as a list of dictionaries?
Each dict describes one device with named fields, and the list holds many devices in order. It also matches the shape of JSON and YAML data.

Key takeaways

  • Lists are ordered and changeable; tuples are ordered and fixed.
  • Dictionaries map keys to values and suit device or interface records.
  • Sets hold unique values and make comparisons (difference, intersection) easy.
  • An inventory is typically a list of dictionaries, the same shape as JSON.
  • Use .get() for optional keys and .copy() when you really need a copy.
Tracks your learning on this device only. See your progress on the learning paths.

About the author

Mohamed Fayas

Founder of FM TecHub. CCNA certified, with a BTEC HND in Network Engineering, and BEng (Hons) in Computer Networking and Cloud Security. He writes practical, plain-English guides on networking, security and cloud.

More about the author

Original content written by Mohamed Fayas for FM TecHub. © 2026 FM TecHub. You're welcome to share a link to this page; please don't copy the text elsewhere without permission.

Stay up to date by email

New notes, tools and security news from FM TecHub, explained simply. Free.

We only use your email to send these updates. See our privacy policy.