Home > Software design >  python dictionary and prettytable module
python dictionary and prettytable module

Time:12-16

Need small help or at least point to right direction. I am writing small function that should print content of a dict in the prettytable format.

Here is code example:

head = ["HOSTNAME", "OS", "PROTOCOL"]

data = {
    'server1': ['ESXi', 'FC'],
    'server2': ['ESXi', 'FC'],
    'server3': ['ESXi', 'FC'],
}

def printify_table(header, data, align='c'):

    x = PrettyTable()
    x.field_names = header
    x.align = align

    for k, v in data.items():
        x.add_row([k, v[0], v[1]])
    print(x)


printify_table(head, data)

Result: python x.py

 ---------- ------ ---------- 
| HOSTNAME |  OS  | PROTOCOL |
 ---------- ------ ---------- 
| server1  | ESXi |    FC    |
| server2  | ESXi |    FC    |
| server3  | ESXi |    FC    |
 ---------- ------ ---------- 

This works fine for now as I have static dict values. No problem there!

Issue| Problem : Now, what would be the pythonic approach to adjust code in case I face different number of values for each key?

In case I come across something like this?

data = {
    'server1': ['ESXi'],
    'server2': ['ESXi', 'FC'],
    'server3': ['ESXi', 'FC','iSCI],
}

How yould you adjust below line?

  x.add_row([k, v[0], v[1]]

I tried with comprehension list but somehow I am struggling to incorporate it. Any feedback appreciated.

CodePudding user response:

You can use * unpacking in lists.

>>> a = [3, 4, 5]
>>> b = [1, 2, *a]
>>> b
[1, 2, 3, 4, 5]

For your case, this would be add_row([k, *v])

CodePudding user response:

Thanks for an excellent question, the world would be a better if people were to think more Pythonian. I think the snippet below will work:

v.extend(['']*(30-len(v)))

Insert it in your for-loop.

  • Related