I receive data like this in a string:
foo = """Port Mac Address group-addr vlan ver
s2p2 0100.5e00.0004 239.0.0.4 1 1
s2p0 0100.5e00.0005 239.0.0.8 1 1
s2p1 0100.5e00.0004 239.0.0.4 1 1"""
I wish to format it in a table. When the data goes in the table I want a separate line for each, unless the latter 4 are the same (mac, group, vlan, ver). If this happens I want the data on one line and print both ports beside each other
Vlan Group Type Version Port List
-----------------------------------------------------------------------
1 239.0.0.4 igmp v1 s2p1, s2p2
1 239.0.0.8 igmp v1 s2p0
I parse the data into a list of dictionaries:
def parse_lines(lines):
headers = lines[0].split()
entries = []
for r in lines[1:]:
if not len(r): continue # skip blank lines
vals = r.split()
e = dict(zip(headers,vals))
entries.append(e)
return entries
def print_table():
print "%s %10s %10s %14s %15s" % ("Vlan", "Group", "Type", "Version", "Port List")
print "---------------------------------------------------------"
if foo is not None:
entries = foo.replace("Mac Address", "Mac-Address")
entries = parse_lines(entries.split("\n"))
This leaves me with a list of dictionaries, an example of the format:
[{'group-addr': '239.0.0.4', 'vlan': '1', 'ver': '1', 'Port': 's2p1', 'Mac-Address': '0100.5e00.0004'}, {'group-addr': '239.0.0.5', 'vlan': '1', 'ver': '1', 'Port': 's2p1', 'Mac-Address': '0100.5e00.0005'}]
How should I process these to compare and store them before printing? Create a new dictionary? Compare the non-port value for equivalence for the whole previous dict and then if they are all the same test the port and add the values to the new dictionary?