Skip to content

Loops

The wonderfully powerful for loop is a fundamental building block in programming. We already learned about how to loop over lists in the previous lesson. Now we shall take a look at how to use for to smartly handle dictionaries.

Dictionaries

In a dictionary we have pair-wise data (the router name and the os type shown below). These pairs are called key-value pairs. The router name is the key and the os type is the value.

Let's see:

Looping over a dictionary - TAKE 1
# we define the dictionary, albeit it looks cleaner than the list of tuples
devices = {
    "router2": "cisco_ios",
    "router17": "cisco_ios",
    "switch11": "cisco_ios",
}

for device in devices:
    print(f"{device = }")
Output
device = 'router2'
device = 'router17'
device = 'switch11'

Hmm... Perhaps not exactly what we were expecting? It was so simple to loop over a list.

It seems that when we loop over a dictionary, we are only getting the keys. But we can fix that by using the items() method of the dictionary, since the method returns both the keys and values, pairwise. Then we can use unpacking to assign each key and value to a separate variable, like we learned when unpacking lists.

Looping over a dictionary - TAKE 2
for item in devices.items():
    device, os = item
    print(f"{device = }\n{os     = }\n")
Output
device = 'router2' 
os     = 'cisco_ios'

device = 'router17'
os     = 'cisco_ios'

device = 'switch11'
os     = 'cisco_ios'

It feels a bit clunky to first get the item and then unpack it... But there is a better way!

We can make it cleaner by unpacking directly in the loop expression:

Looping over a dictionary - TAKE 3
for device, os in devices.items():
    print(f"{device = }\n{os     = }\n")
Output
device = 'router2'
os     = 'cisco_ios'

device = 'router17'
os     = 'cisco_ios'

device = 'switch11'
os     = 'cisco_ios'

Same output, but much cleaner code! This is the preferred way of looping over dictionaries.

Key Points

  • The for loop is a powerful tool for iterating over different data types.
  • When looping over a dictionary, you can use the items() method to get key-value pairs.
  • You can unpack key-value pairs directly in the loop expression for cleaner code.