Network Automation Example - Finditer With Counter | zeroslash.io

Network Automation Example - Finditer With Counter

Submitted by zeroslash on Thu, 12/27/2018 - 11:10

Still using the same example data that I've been using in my previous Network Automation examples, this time around I try out a counting scenario.

In this example, I wanted a quick and easy way to just zip through the text and count how many interfaces of a certain type I will find.

I'm using the re.finditer() function to give me an iterable of all matches (line 16).

I then pass its result to Counter() to keep track of all the counts (line 21). If there's more to count it's easy to just update the counter (line 23).

Just a note on re.finditer(), if you know re.findall(), re.finditer() is kind of the iterator version of that (as the name implies), compared to re.findall() which returns a list.

I can keep on updating the Counter() object and keep track of any additional interfaces. However, I'm keeping it simple with my overused example data :)

I think this example is pretty simple but I just find re.finditer() ( or even re.findall() ) to be a good match with Counter() for such cases.

Code:

Output:

Counter({'GigabitEthernet': 5})
Counter({'GigabitEthernet': 5, 'FastEthernet': 4})