Network Automation Example - Finditer With Defaultdict | zeroslash.io

Network Automation Example - Finditer With Defaultdict

Submitted by zeroslash on Sat, 04/27/2019 - 01:40

In this example, I explored another approach to using Finditer to count network interfaces in my last post. I recommend you check that out first before going through this one.

Here I combined re.finditer() with defaultdict() instead, keeping the matched patterns associated with the keyword we are looking for.

Having it in such a way probably doesn't provide much value as we are only after the count - the len(). But the point here is to explore alternatives and sort of find different paths to the same destination. Understanding which one's better is something I'm really curious about so that's why I'm playing around with these different styles.

Code:

As you can see I specified the keywords of interest in a tuple (line 15) and iterated over that (line 17). Then executed re.finditer() and iterated through the matches (line 18) after which I save them (line 19) into the defaultdict() object I created (line 14). It's intended to store list() objects (line 14) and hence the append() for each matched pattern (line 19). The pattern we are looking for is used as the key as well (int_index[interface] where interface is either 'GigabitEthernet' or 'FastEthernet'), to store all the matches.

Finally, just getting the len() of each value per key (line 22) will provide us with the match counts we are looking for.

Output:

GigabitEthernet 5
FastEthernet 4