Search code examples
printingpython-3.6defaultdict

Printing k, v from a defaultdict(list)


I have a program that connects via SSH (Paramiko library) to a Cisco Wireless LAN Controller (WLC). I then run a 'show client summary' and parse\process the output to generate a report.

Everything works except the printing.

NOTE: 'e' is a dictionary created with: defaultdict(list)

If I use this:

for k, v in e.items():
    print('{:25}'.format(k), end='')
    for i in v:
        print('{:5}'.format(i), end='')
    print("\n")

The output looks like this:

       AP                Count
------------------------------
AP0027.e3f1.9208             8    7    6

AP70df.2f42.3450             1    1    1

AP25-AthleticOffice          4    4    3

AP70df.2f74.9868             1    1    1

AP70df.2f42.3174             2    2    2

I don't want the extra blank line between the data lines.

But if I simply get rid of the last line: print("\n"),

then I get this format for the output:

AP0027.e3f1.9208             8    7    6AP70df.2f42.3450             1    1    1AP25-AthleticOffice          4    4    3AP70df.2f42.3174             1    1    1AP70df.2f42.3174             2    2    2

No carriage return.

I am either getting zero carriage return or two.


Solution

  • This happens because print() already appends the end character - which is \n by default. You can fix it by printing just an empty string (which is the same as print('', end='\n')):

    for k, v in e.items():
        print('{:25}'.format(k), end='')
        for i in v:
            print('{:5}'.format(i), end='')
        print('')