From point A to point B
Point A: you already know dictionaries, strings and lists, and you know what a method is. But you still write a loop over a list to do something Python handles in one line. Point B: by the end of this chapter, you'll know the most useful methods of these 3 types. And you'll pick the right one to process inventories, logs and IP addresses.
You don't need to memorize them. It's enough to know they exist so you can look them up when you need them.
Why revisit these objects
When you first met numbers, strings, lists, tuples and dictionaries, you didn't know what a class was yet. Now you do: each of those values is an object of a class, and its class gives it methods.
A method is a function that belongs to the object, and you call it with a dot: text.upper(). In this chapter, you'll go through the methods you'll use most when you automate a network.
In the documentation, you'll see signatures like get(key, default=None) or count(sub[, start[, end]]). The square brackets mark optional parameters: you don't type them when you call the method.
Dictionaries: read, check, loop and delete
Imagine an API returns an interface's data as a dictionary. These are the basic operations:
iface = {"name": "Gi0/1", "vlan": 10, "status": "up"}
# get: a default value instead of KeyError
print(iface.get("vlan")) # → 10
print(iface.get("mtu")) # → None
print(iface.get("mtu", 1500)) # → 1500
# in: checks whether a key exists
print("status" in iface) # → True
print("description" in iface) # → False
# keys(), values(), items()
print(iface.keys()) # → dict_keys(['name', 'vlan', 'status'])
print(iface.values()) # → dict_values(['Gi0/1', 10, 'up'])
print(iface.items()) # → dict_items([('name', 'Gi0/1'), ('vlan', 10), ('status', 'up')])
for key, value in iface.items():
print(f"{key:>7}: {value}")
# pop: deletes the key and returns its value
status = iface.pop("status")
print(status, iface) # → up {'name': 'Gi0/1', 'vlan': 10}
print(iface.pop("mtu", 1500)) # → 1500
The for loop prints this:
name: Gi0/1
vlan: 10
status: up
d.get(k, default)works liked[k]. The difference: if the key doesn't exist, it returns the default value (orNone) instead of raisingKeyError. It's ideal for optional fields in a JSON response.d.pop(k, default)removes the key and hands you its value. Without a default, a missing key raisesKeyError.d.items()gives you key-value pairs; it's the usual way to loop over a dictionary.
D.has_key(k); that method no longer exists in Python 3, so use k in D. Also, keys(), values() and items() no longer return lists but views: lightweight objects that always reflect the dictionary. If you need a list, convert it with list(). Since Python 3.7, dictionaries keep insertion order as part of the language.A view isn't a copy. If the dictionary changes, the view changes with it:
iface = {"name": "Gi0/1", "vlan": 10}
keys = iface.keys()
print(keys) # → dict_keys(['name', 'vlan'])
iface["status"] = "up"
print(keys) # → dict_keys(['name', 'vlan', 'status'])
print(list(keys)) # → ['name', 'vlan', 'status']
Dictionaries: merge and accumulate
When you automate, you often start from a default configuration and override it with each device's settings. Python 3.9 added operators for that (PEP 584):
defaults = {"mtu": 1500, "status": "down", "vlan": 1}
config = {"status": "up", "vlan": 20}
# | creates a new dict; if a key repeats, the right side wins
final = defaults | config
print(final) # → {'mtu': 1500, 'status': 'up', 'vlan': 20}
# |= updates the dict on the left (like update)
defaults |= {"mtu": 9000}
print(defaults) # → {'mtu': 9000, 'status': 'down', 'vlan': 1}
# setdefault: returns the key or creates it with an initial value
vlans = {}
vlans.setdefault(10, []).append("Gi0/1")
vlans.setdefault(10, []).append("Gi0/2")
print(vlans) # → {10: ['Gi0/1', 'Gi0/2']}
# update and popitem
r = {"hostname": "R1"}
r.update(model="ISR4331", ip="10.0.0.1")
print(r) # → {'hostname': 'R1', 'model': 'ISR4331', 'ip': '10.0.0.1'}
print(r.popitem()) # → ('ip', '10.0.0.1')
setdefault is handy for grouping: here it collects each VLAN's interfaces without first checking whether the list exists. popitem() removes and returns the last pair inserted.
Strings: find, count and replace
Syslog messages are text. These methods help you analyze them. Remember that strings are immutable: no method changes the original string; they all return a new one.
log = "%LINK-3-UPDOWN: Interface Gi0/1, changed state to down"
print(log.count("a")) # → 3
print(log.count("a", 30)) # → 2
print(log.find("Interface")) # → 16
print(log.find("VLAN")) # → -1
print(log.partition(": "))
# → ('%LINK-3-UPDOWN', ': ', 'Interface Gi0/1, changed state to down')
print(log.partition(" | "))
# → ('%LINK-3-UPDOWN: Interface Gi0/1, changed state to down', '', '')
print(log.replace("down", "up"))
# → %LINK-3-UPDOWN: Interface Gi0/1, changed state to up
s.count(sub, start, end)counts how many timessubappears. Withstartandend, you limit the search to a slice.s.find(sub)returns the position of the first match, or-1if it isn't there. If you only want to know whether it appears,"VLAN" in logis clearer.s.partition(sep)splits at the first separator and always returns a 3-item tuple: before, separator and after. If it doesn't find the separator, the whole text goes in the first position.s.replace(old, new, count)replaces every match, or only the firstcountones.
Strings: split and join
split and join are opposite operations. With them, you take an IP address apart and put it back together:
ip = "192.168.10.1"
octets = ip.split(".")
print(octets) # → ['192', '168', '10', '1']
print(ip.split(".", 1)) # → ['192', '168.10.1']
print(" R1 R2 R3 ".split()) # → ['R1', 'R2', 'R3']
print(".".join(octets)) # → 192.168.10.1
print(", ".join(["Gi0/1", "Gi0/2"])) # → Gi0/1, Gi0/2
With no arguments, split() splits on any run of spaces, tabs or newlines, and drops the empty pieces. The second argument limits the number of splits. Notice the shape of join: you call it on the separator, and it takes the sequence of strings.
Python 3 added other methods you'll use every day. removeprefix and removesuffix arrived in Python 3.9 (PEP 616):
print("Gi0/1".removeprefix("Gi")) # → 0/1
print("router-01.lab.local".removesuffix(".lab.local")) # → router-01
print("Gi0/1".removeprefix("Te")) # → Gi0/1 (unchanged)
print(" R1 \n".strip()) # → R1
print("show ip route".startswith("show")) # → True
print("backup.cfg".endswith((".cfg", ".txt"))) # → True
print("ROUTER-01".lower(), "r1".upper()) # → router-01 R1
print("4096".isdigit(), "40a6".isdigit()) # → True False
print("Gi0/1".rjust(8, ".")) # → ...Gi0/1
print("a,b,,c".rsplit(",", 1)) # → ['a,b,', 'c']
Use removeprefix instead of strip("Gi"): strip removes individual characters from a set, not an exact prefix, and it can delete more than you expect.
str and unicode), and the string module had functions like string.split(s). In Python 3, str is always Unicode, binary data goes in bytes, and those string module functions no longer exist: always use the string's methods.Lists: add, find and remove
Unlike strings, lists are mutable. Almost all their methods modify the list itself and return None.
vlans = [10, 20]
vlans.append(30)
print(vlans) # → [10, 20, 30]
vlans.extend([40, 20])
print(vlans) # → [10, 20, 30, 40, 20]
print(vlans.count(20)) # → 2
print(vlans.index(20)) # → 1
print(vlans.index(20, 2)) # → 4
vlans.insert(0, 1)
print(vlans) # → [1, 10, 20, 30, 40, 20]
print(vlans.pop()) # → 20
print(vlans.pop(0)) # → 1
vlans.remove(30)
print(vlans) # → [10, 20, 40]
vlans.reverse()
print(vlans) # → [40, 20, 10]
append(x)adds one item at the end;extend(iterable)adds each item of the iterable.count(x)counts occurrences;index(x, start, end)returns the position of the first one, or raisesValueErrorif it isn't there.insert(i, x)placesxat positioni.pop(i)removes and returns the item at positioni; with no argument, the last one.remove(x)deletes the first occurrence ofx.reverse()reverses the list in place, without making a copy.
A classic mistake is writing vlans = vlans.append(50). Since append returns None, you lose the list.
Lists: sort with key
sort() sorts the list in place. With reverse=True, it sorts from highest to lowest. The key parameter takes a function that extracts, from each item, the value to compare by:
import ipaddress
routers = [
{"hostname": "R3", "uptime_h": 12},
{"hostname": "R1", "uptime_h": 340},
{"hostname": "R2", "uptime_h": 72},
]
routers.sort(key=lambda r: r["uptime_h"])
print([r["hostname"] for r in routers]) # → ['R3', 'R2', 'R1']
routers.sort(key=lambda r: r["uptime_h"], reverse=True)
print([r["hostname"] for r in routers]) # → ['R1', 'R2', 'R3']
# sorted() returns a new list and accepts any iterable
ips = ["10.0.0.20", "10.0.0.3", "10.0.0.100"]
print(sorted(ips))
# → ['10.0.0.100', '10.0.0.20', '10.0.0.3']
print(sorted(ips, key=ipaddress.ip_address))
# → ['10.0.0.3', '10.0.0.20', '10.0.0.100']
The last example shows why key matters. Sorted as text, the IPs come out wrong because they're compared character by character. With key=ipaddress.ip_address, each string becomes a real address and the order is numeric. You'll see the lambda expression in the next chapter.
L.sort(cmp=None, key=None, reverse=False), with a cmp function that returned -1, 0 or 1. Python 3 removed the cmp parameter: today sort(cmp=...) raises TypeError. Use key, which is faster. If you inherit an old comparison function, adapt it with functools.cmp_to_key.How to discover methods on your own
You don't need to remember everything. The interpreter tells you:
>>> [m for m in dir(str) if m.startswith("remove")]
['removeprefix', 'removesuffix']
>>> help(dict.get)
Help on method descriptor get:
get(self, key, default=None, /) unbound builtins.dict method
Return the value for key if key is in the dictionary, else default.
dir(object) lists its attributes and methods, and help() shows its documentation. Press q to exit the help. It takes practice, but looking things up this way is more reliable than relying on memory.
Challenge
Answer before you open the solution.
1. A Python 2 script uses if data.has_key("vlan"):. How do you write it in Python 3?
if "vlan" in data: The has_key method no longer exists; the in operator does the same job.
2. A JSON response sometimes includes "description" and sometimes doesn't. How do you read it without crashing the program?
With data.get("description", ""). If the key is missing, you get an empty string instead of a KeyError.
3. What does "10.1.1.1".split(".", 1) return?
['10', '1.1.1']. The second argument limits the number of splits to 1.
4. You write vlans = vlans.sort() and then print(vlans). What do you see, and why?
None. sort() sorts in place and returns None. Use vlans.sort() without assigning, or vlans = sorted(vlans).
5. You have base = {"mtu": 1500} and extra = {"mtu": 9000}. What's the value of (base | extra)["mtu"]?
9000. With |, if a key appears in both dictionaries, the one on the right wins.
Key takeaways
- Dictionaries:
getwith a default value,ininstead ofhas_key,items()to loop andpopto remove. keys(),values()anditems()return views; uselist()if you need a list.|and|=merge dictionaries; the value on the right wins.- Strings:
find,count,partition,replace,split,join,removeprefixandremovesuffix. They always return a new string. - Lists:
append,extend,insert,pop,remove,index,countandreversemodify the list in place. - To sort, use
key=; thecmpparameter no longer exists.
In the next chapter, you'll treat functions as data: lambda, map, comprehensions, generators and decorators.
Official resources
- Mapping types: dictdocs.python.org
- String methodsdocs.python.org
- More on listsdocs.python.org
- Sorting techniquesdocs.python.org
- PEP 584: Add union operators to dictpeps.python.org
- PEP 616: String methods to remove prefixes and suffixespeps.python.org
Source and credits. This course is based on the book Python para todos by Raúl González Duque, published under the Creative Commons Attribution 2.5 Spain license. The original book was written for Python 2.5. Jesús Espinoza, with AI assistance, brought it to Python 3.14: he rewrote every chapter in his own words, replaced the examples with networking cases, updated the syntax and the modules that no longer exist, fixed errors in the original and tested all the code with Python 3.14.6 against the official documentation.