Skip to content

Lab 15 - Getting Started with For Loops

This lab walks you through an introduction of using for loops to iterate over a list of strings, a dictionaries, and finally, a list of dictionaries.

Task 1 - Print Data with a For Loop

The first task you will do is to loop through a list and print each element to the terminal.

Step 1-1

Start a new Python interpreter session, then create the following list of commands:

>>> commands = ['interface Eth2/1', 'description Configured by Python', 'speed 100', 'duplex full']
>>>

Step 1-2

Loop through commands and print each element out:

>>> for command in commands:
...      print(command)
...
interface Eth2/1
description Configured by Python
speed 100
duplex full
>>>

Step 1-3

Now try this again using a different variable than command. Use for item in commands: instead:

>>> for item in commands:
...     print(item)
...
interface Eth2/1
description Configured by Python
speed 100
duplex full
>>>

Remember that the variable name that comes after the for keyword is arbitrary (i.e. you get to choose it).

Step 1-4

Create a list of routers and loop through them printing the following status message for each device:

Connecting to device | csr1

But replace csr1 with the correct hostname as you're looping through.

>>> routers = ['csr1', 'csr2', 'csr3']
>>>
>>> for router in routers:
...     print("Connecting to device | {}".format(router))
...
Connecting to device | csr1
Connecting to device | csr2
Connecting to device | csr3
>>>

Step 1-5

Update the previous loop to ensure each hostname is "uppercase":

>>> for router in routers:
...     print("Connecting to device | {}".format(router.upper()))
...
Connecting to device | CSR1
Connecting to device | CSR2
Connecting to device | CSR3
>>>

Task 2 - Loop over a Dictionary

Step 2-1

Create a dictionary that stores information about a network interface that will be configured. The keys will be parameters/features and the values will be the specific commands to send to the device.

Create this dictionary:

>>> interface = {}
>>> interface['duplex'] = 'full'
>>> interface['speed'] = '100'
>>> interface['description'] = 'Configured by Python'
>>>
>>> print(interface)
{'duplex': 'full', 'speed': '100', 'description': 'Configured by Python'}
>>>

Step 2-2

Loop through interface, print the keys, values, and then the keys and values together.

Print the Keys:

>>> for key in interface.keys():
...      print(key)
...
duplex
speed
description
>>>

Step 2-3

Print the Values:

>>> for value in interface.values():
...     print(value)
...
full
100
Configured by Python
>>>

Step 2-4

Print the Keys & Values:

>>> for key, value in interface.items():
...     print(key, '--->', value)
...
duplex ---> full
speed ---> 100
description ---> Configured by Python
>>>

Note that using items gives you access to each item and remember that items returns a list of tuples (you can also think of this as a list of lists from an usability perspective). Here key maps to the first element in each tuple and value maps to the second in element in each tuple.

Remember key and value are user defined - this also works just fine:

>>> for feature, configured_value in interface.items():
...     print(feature, '--->', configured_value)
...
duplex ---> full
speed ---> 100
description ---> Configured by Python
>>>

Task 3 - Loop over a List of Dictionaries

In this task, we will build a list of elements. Each element will represent a VLAN configuration, that consists of the vlan id and vlan name.

Step 3-1

Create the VLAN dictionaries:

>>> vlan10 = {'name': 'web', 'id': '10'}
>>> vlan20 = {'name': 'app', 'id': '20'}
>>> vlan30 = {'name': 'db', 'id': '30'}

Step 3-2

Create the list of VLANs. Remember, this will be a list of dictionaries since each VLAN is a dictionary.

>>> vlans = [vlan10, vlan20, vlan30]
>>>

Step 3-3

Print the vlans variable to see what you just created:

>>> print(vlans)
[{'name': 'web', 'id': '10'}, {'name': 'app', 'id': '20'}, {'name': 'db', 'id': '30'}]
>>>

Step 3-4

Pretty print the vlans list:

>>> import json
>>>
>>> print(json.dumps(vlans, indent=4))
[
    {
        "name": "web",
        "id": "10"
    },
    {
        "name": "app",
        "id": "20"
    },
    {
        "name": "db",
        "id": "30"
    }
]
>>>

Step 3-5

Loop over vlans and print each element.

>>> for vlan in vlans:
...     print(vlan)
...
{'name': 'web', 'id': '10'}
{'name': 'app', 'id': '20'}
{'name': 'db', 'id': '30'}
>>>

You can see that each element is a dictionary.

Step 3-6

You can verify it by using the type() statement in the for loop.

>>> for vlan in vlans:
...     print(vlan)
...     print(type(vlan))
...
{'name': 'web', 'id': '10'}
<class 'dict'>
{'name': 'app', 'id': '20'}
<class 'dict'>
{'name': 'db', 'id': '30'}
<class 'dict'>
>>>

Step 3-7

Since you understand the data type of this object now, print the following by using a for loop:

vlan 10
 name web
vlan 20
 name app
vlan 30
 name db
>>> for vlan in vlans:
...     print("vlan {}".format(vlan['id']))
...     print(" name {}".format(vlan['name']))
...
vlan 10
 name web
vlan 20
 name app
vlan 30
 name db
>>>