Iterating through two lists at the same time – Python

If doing a show inventory on a Cisco device, the output looks as follows (hostnames and serials changed to protect the innocent)

foo.bar1#sh inv
NAME: "Chassis", DESCR: "Cisco 7204VXR, 4-slot chassis"
PID: CISCO7204VXR      , VID:    , SN: 35246813

NAME: "NPE-G2 0", DESCR: "Cisco 7200 Series Network Processing Engine NPE-G2"
PID: NPE-G2            , VID: V03 , SN: FOO16810684

NAME: "disk2", DESCR: "256MB Compact Flash Disk for NPE-G2"
PID: MEM-NPE-G2-FLD256 , VID:    , SN:

NAME: "Power Supply 1", DESCR: "Cisco 7200 AC Power Supply"
PID: PWR-7200-AC       , VID:    , SN:

I can read the output and via regular expressions, extract the needed information. Let’s say I want to grab the PID references as well as the serial numbers associated with it. Note that not every single PID has a serial number.

When creating a re.findall regular expression in Python, the results are fed back via a list. As an example:

>>> h = re.findall(r'pid:[\s\t]{0,3}[a-z0-9\-]{0,12}', text, re.IGNORECASE)
>>> h
['PID: CISCO7204VXR', 'PID: NPE-G2', 'PID: MEM-NPE-G2-F', 'PID: PWR-7200-AC']
>>> s = re.findall(r'sn:[\s\t]{0,3}[a-z0-9]{0,20}[?!\n\t\s]', text, re.IGNORECASE)
>>> s
['SN: 35246813\n', 'SN: FOO16810684\n', 'SN:\n\n']

I would like to print out the hardware, but followed immediately by the serial number field, even if a serial doesn’t exist. Essentially I need to iterate through both the hardware and serial lists at the same time. If I try to one at a time, I’ll just get all the PIDs lumped together while all the serial numbers lumped together.

Python makes this very easy to go through both at the same time:

h = re.findall(r'pid:[\s\t]{0,3}[a-z0-9\-]{0,12}', text, re.IGNORECASE)
s = re.findall(r'sn:[\s\t]{0,3}[a-z0-9]{0,20}[?!\n\t\s]', text, re.IGNORECASE)
>>> for i,j in zip(h,s):
	print(i+"\n"+j)

	
PID: CISCO7204VXR
SN: 35246813

PID: NPE-G2
SN: FOO16810684

PID: MEM-NPE-G2-F
SN:

Short and Sweet

© 2009-2020 Darren O'Connor All Rights Reserved -- Copyright notice by Blog Copyright