Site icon Karneliuk

CEX (Code EXpress) 07. Loops are bad in the networks, but not in code.

Hello my friend,

We have covered all the necessary types of the Python’s variables (ordinary, lists and dictionaries) and now we can move on with further concepts. And the first immediate pit stop is the question “how can we work with the Python’s lists and dictionaries efficiently?” The answer wold be “just loop them”!

Network automation training – boost your career

Don’t wait to be kicked out of IT business. Join our network automation training to secure your job in future. Come to NetDevOps side.

How does the training differ from this blog post series? Here you get the basics and learn some programming concepts in general, whereas in the training you get comprehensive set of knowledge with the detailed examples how to use Python for the network and IT automation. You need both.

What are we going to do today?

The looping of the sibling’s element out of any data structure, such as a Python’s list or a dictionary, is one of the essential building blocks of any programming code, including the simplest ones. Therefore, today you will learn:

If you are a bit familiar with any programming language, you might know that there are typically two major approaches to create a loops: for and while. We start today with for instruction, because it is easier to start with that and it is used in the scenario of working with a Python’s list and dictionary.

The while instruction will be covered in the future posts in the Code EXpress (CEX) series.

Feeling excitement? So do we!

If you want to know how to install Python 3.8, check the corresponding blogpost.

Why does it matter?

Within the network automation (or any other sort of automation) you may constantly see the repetitive tasks. For example, the following cases are very common:

We are pretty sure that you can continue listing such examples just looking back to the most recent operational tasks you have to do. That is why capability to loop your Python’s lists and dictionaries is a key for your successful code’s execution.

How are we doing that?

Following the approach, we have started earlier, we create a new directory in our GitHub Python’s lessons:


1
2
3
4
$ cd CEX
$ mkdir 07
$ cd 07
$

Inside the directory we create a new file called lists.py, which we will use during this class:


1
2
3
$ touch loop.py && chmod a+x loop.py
$ cat loop.py
#!/usr/local/bin/python3.8

If you have a question to chmod command or to the path to the Python interpreter, take a look on the corresponding class .

Once our Python’s starting file is ready, we can start working with the for loops themselves.

#1. Using for instruction to loop Python’s list

The first case, which you will see in this article is about the usage of the for instruction to create a loop for Python’s list. The syntax is pretty straightforward as demonstrated in the example below:


1
2
3
4
5
6
7
8
9
$ cat loop.py
#!/usr/local/bin/python3.8

interfaces = ['Ethernet1', 'Ethernet2', 'Ethernet3']

print('The list of the interfaces:')

for interface in interfaces:
    print('Your interfaces is {}'.format(interface))

The logic is the following:

Let’s execute this Python’s code:


1
2
3
4
5
$ ./loop.py
The list of the interfaces:
Your interfaces is Ethernet1
Your interfaces is Ethernet2
Your interfaces is Ethernet3

As an outcome of this script’s execution you see multiple strings printed, where each string contains a formatted string where the value of the elements from the original Python’s list are used one at a time.

The next step would be a modification of the list more complex in terms that the elements of the list become mini dictionaries:


1
2
3
4
5
6
7
8
9
10
$ cat loop.py
#!/usr/local/bin/python3.8

interfaces = [{'name': 'Ethernet1'}, {'name': 'Ethernet2'}, {'name': 'Ethernet3'}]

print('The list of the interfaces:')

for interface in interfaces:
    print('Your interfaces is {}'.format(interface))
    print('More precisely {}'.format(interface['name']))

In such a scenario, in each iteration of the for loop the interface gets a value of the iterated element, which is a dictionary by itself. Therefore, to go further alongside the tree inside the dictionary you need to use the Python’s dictionary syntax.

To learn more about joint Python’s list and dictionary data structures you can in the corresponding article

The result of this Python’s code execution is the following:


1
2
3
4
5
6
7
8
$ ./loop.py
The list of the interfaces:
Your interfaces is {'name': 'Ethernet1'}
More preciesly Ethernet1
Your interfaces is {'name': 'Ethernet2'}
More preciesly Ethernet2
Your interfaces is {'name': 'Ethernet3'}
More preciesly Ethernet3

Once you print the whole element using interface variable, you got the whole dictionary content. However, when you call the specific value using interface[‘name’], then you get only this specific value.

#2. Using for instruction and items() function to loop Python’s dictionary

The beauty of the software development and therefore the programming in the Python is that you have an absolute freedom to choose a solution: there are no good or bad ones. There are just more efficient and less.

That’s why you can follow the different approach how you document your interfaces inside the Python data structures, if you wish. You can create a Python’s dictionary like the following one:


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
$ cat loop.py
#!/usr/local/bin/python3.8

# Some code is truncated for brevity

interfaces2 = {
                'Ethernet1': {
                               'speed': 10000,
                               'enabled': True
                             },
                'Ethernet2': {
                               'speed': 10000,
                               'enabled': True
                             },
                'Ethernet3': {
                               'speed': 10000,
                               'enabled': True
                             }
              }

The interaces2 is a standard Python’s dictionary, pretty much the same we have in the previous blogpost. Despite it is not a list, you can create a specific sort of list out of it using items() function. You can assign the result of this function’s execution to a variable or use it directly in the for instruction as illustrated below:


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
$ cat loop.py
#!/usr/local/bin/python3.8

# Some code is truncated for brevity

interfaces2 = {
                'Ethernet1': {
                               'speed': 10000,
                               'enabled': True
                             },
                'Ethernet2': {
                               'speed': 10000,
                               'enabled': True
                             },
                'Ethernet3': {
                               'speed': 10000,
                               'enabled': True
                             }
              }

print('The dictionary of the interfaces:')

for interface_key, interface_value in interfaces2.items():
    print('Internface {} has {} speed and it is {}ly enabled'.format(interface_key, interface_value['speed'], interface_value['enabled']))

In this snippet above you see that the for instruction now have two temporary variables: interface_key and interface_value. The first one will contain the key’s name, whereas the second will have a key’s value:


1
2
3
4
5
6
7
8
9
10
11
12
$ ./loop.py
The list of the interfaces:
Your interfaces is {'name': 'Ethernet1'}
More precisely Ethernet1
Your interfaces is {'name': 'Ethernet2'}
More precisely Ethernet2
Your interfaces is {'name': 'Ethernet3'}
More precisely Ethernet3
The dictionary of the interfaces:
Internface Ethernet1 has 10000 speed and it is Truely enabled
Internface Ethernet2 has 10000 speed and it is Truely enabled
Internface Ethernet3 has 10000 speed and it is Truely enabled

As you see, you can operate now both with the key’s name and the key’s value, which can be a nested Python’s dictionary itself.

If you prefer video

If you prefer watching the video instead of reading blogpost, that is also wonderful. We value your time and want to create for you the best experience possible. Therefore, for all the blogposts associated with CEX series, we will record the video and post it on our YouTube channel.

And here is the video for this blogpost:

What else shall you try?

Programming is all around testing, trying, breaking and fixing the things. Try to do the following things to collect some more experience:

Lessons in GitHub

You can find the final working versions of the files from this blog at our GitHub page.

Conclusion

Make sure you have familiarized yourself with both cases, because they form the basis of the efficient work with the structured data, such as YANG data models, REST API calls and so on. Together with the conditionals, which will be covered in the next blogpost, the loops are the must have tool in your network automation developer’s toolkit. Take care and goodbye!

Support us






P.S.

If you have further questions or you need help with your networks, I’m happy to assist you, just send me message. Also don’t forget to share the article on your social media, if you like it.

BR,

Anton Karneliuk 

Exit mobile version