Network Automation Example - Groupby | zeroslash.io

Network Automation Example - Groupby

Submitted by zeroslash on Wed, 05/16/2018 - 07:45

In this example, again I’m using the same data as with my 2 previous posts ( Namedtuple and Generators With Filtering). However, I’m trying to group them by interfaces. In this case, it will be FastEthernet and GigabitEthernet.

I’m still using the same generator function (lines 14-17), I then sorted it (line 20) and used the itertools function groupby() to group them by name (line 23).

The sort() (line 20) before groupby() here is crucial. This is because groupby() only works on sequential identical values such as “AABBBCC”. It won’t work properly on something like “AABCBBC”. So the order is very important prior to grouping them together.

It’s also worth noting that i used the operator function itemgetter() as the optional key to my sorted() (line 20) and groupby() (line 23) functions. Its use is pretty much the same as “lambda var: var[‘key’]”.

 

Last but not the least I show you how the same thing can be achieved using a simple defaultdict (line 31). I basically just used the name key in each dictionary to group everything into 'FastEthernet' and 'GigabitEthernet', both being used as keys in the defaultdict. Each row entry with the same name key gets appended to its matching defaultdict key (line 34).

Code:

Output:

using groupby:
FastEthernet
     {'name': 'FastEthernet', 'number': '1/0/1', 'error': 23}
     {'name': 'FastEthernet', 'number': '1/1/1', 'error': 11}
     {'name': 'FastEthernet', 'number': '2/1/0', 'error': 42}
     {'name': 'FastEthernet', 'number': '3/3/1', 'error': 781}
GigabitEthernet
     {'name': 'GigabitEthernet', 'number': '4/0/0', 'error': 89}
     {'name': 'GigabitEthernet', 'number': '4/1/0', 'error': 142}
     {'name': 'GigabitEthernet', 'number': '3/2/0', 'error': 142}
     {'name': 'GigabitEthernet', 'number': '0/2/0', 'error': 142}
     {'name': 'GigabitEthernet', 'number': '5/1/0', 'error': 46}
using defaultdict:
FastEthernet
     {'name': 'FastEthernet', 'number': '1/0/1', 'error': 23}
     {'name': 'FastEthernet', 'number': '1/1/1', 'error': 11}
     {'name': 'FastEthernet', 'number': '2/1/0', 'error': 42}
     {'name': 'FastEthernet', 'number': '3/3/1', 'error': 781}
GigabitEthernet
     {'name': 'GigabitEthernet', 'number': '4/0/0', 'error': 89}
     {'name': 'GigabitEthernet', 'number': '4/1/0', 'error': 142}
     {'name': 'GigabitEthernet', 'number': '3/2/0', 'error': 142}
     {'name': 'GigabitEthernet', 'number': '0/2/0', 'error': 142}
     {'name': 'GigabitEthernet', 'number': '5/1/0', 'error': 46}