Python Dictionaries_ A Network Engineer’s Guide — Python for Network Engineer
Python Dictionaries_ A Network Engineer’s Guide — Python for Network Engineer
Network Engineer’s
Guide
Contents
Python Dictionaries: A Network Engineer’s Guide
Similarities with Lists: Mutability
Using Curly Braces to Create a Dictionary
Navigating Dictionaries in Python
Dictionary Toolbox: Methods
Exploring Keys, Values, and Items
Dynamic Modifications with .pop()
Deletion Strategies: del and update
Dictionary Iteration Techniques
Nested Dictionaries in Python
my_dict = {
"rtr1": "10.100.1.2",
"rtr2": "10.100.2.1",
"rtr3": "10.100.3.1",
}
# Output: {'rtr1': '10.100.1.2', 'rtr2': '10.100.2.1', 'rtr
If you try to access a key that doesn’t exist, you’ll get a KeyError .
To avoid this, use the get() method, which returns None if the
key is missing:
Dictionaries are not just for retrieving values; you can also update
them. To change the value of an existing key, simply reassign it:
# Example Usage
value = my_dict.pop("rtr1")
This method gets the value for the specified key and removes the
key-value pair from the dictionary.
# Example Usage
del my_dict["rtr2"]
stable
The ** update() Method
The update() method merges dictionaries and updates existing
keys with new values:
# Example Usage
new_data = {"rtr3": "10.100.4.1", "rtr4": "10.100.5.1"}
my_dict.update(new_data)
# Example Usage
for k in my_dict:
print(k)
This loop prints each key in the dictionary. To iterate over values,
use the .values() method:
# Example Usage
for v in my_dict.values():
print(v)
This loop prints each value in the dictionary. To iterate over both
keys and values, use the .items() method:
Dictionary of Dictionaries
You can have a dictionary where each key’s value is another
dictionary. This helps you organize information neatly:
my_devices = {
'rtr1': {
'host': 'device1',
'device_type': 'cisco',
},
'rtr2': {
'host': 'device2',
'device_type': 'junos',
}
}
Here, each router (‘rtr1’ and ‘rtr2’) has its own dictionary with
details like ‘host’ and ‘device_type’.
sf = {
'routers': ['192.168.1.1', '192.168.1.2'],
'switches': ['192.168.1.20', '192.168.1.21']
}
network_devices = [
{'device_type': 'router', 'ip': '192.168.1.1'},
{'device_type': 'switch', 'ip': '192.168.1.20'}
]
stable