Python Dictionaries
Dictionaries
Python dictionaries are data structure that is similar to lists. However, instead they are made up keys and associated values.
When for lists, you need to know the item sequence to be able to call it. For dictionaries, you call the key…which often easier.
The format is {“key”:”value”}, let’s look at some examples. In the 1st one, I create a list called ROUTERS and add R1, R2 and R3 associated with their type. Then I print the content of my dictionary.
ROUTERS = {"R1":"IOS", "R2":"XR", "R3":"NX-OS"}
print((ROUTERS))
#Output will be:
{'R1': 'IOS', 'R2': 'XR', 'R3': 'NX-OS'}
In the next example, I would like to know what type of router is R2. Pay attention to the syntax, where “R2” is between square brackets and not curly ones.
ROUTERS = {"R1":"IOS", "R2":"XR", "R3":"NX-OS"}
print(ROUTERS["R2"])
#
Output will be:
XR
Adding to dictionaries
Adding to dictionaries consist of simply adding the new key value pair as per this example. Here, I am adding a new router R4, which is an ISR type.
ROUTERS = {"R1":"IOS", "R2":"XR", "R3":"NX-OS"}
ROUTERS["R4"] = "ISR"
print(ROUTERS)
#Output will be:
{'R1': 'IOS', 'R2': 'XR', 'R3': 'NX-OS', 'R4': 'ISR'}
Dictionaries Content
In this next example, we want to print or list all keys in a dictionary, but without the matching values.
devices = {"R1":"ios", "R2":"xr", "R3":"nx-os"}
for items in devices:
print (items)
#Output:
R1
R2
R3
Now, we would like to list the values only.
devices = {"R1":"ios", "R2":"xr", "R3":"nx-os"}
for key,value in devices.items():
print (value)
Python crash course video
To learn more about Python for Engineers, watch this 1hr crash course video.
This course covers foundation topics: