1

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.

Z DZ
  • 13
  • 2
  • Depending which python version you're using, you can use `[k, *v]` but how would that work for the fixed number of headings? – Holloway Dec 16 '21 at 11:55
  • Thanks Holloway, its python 3.8 and *v is solving my (first) issue. So simple but very effective. Thanks once more. Yeah, heading problem would be next one :). – Z DZ Dec 16 '21 at 12:02

2 Answers2

0

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])

Holloway
  • 6,412
  • 1
  • 26
  • 33
0

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.

user23952
  • 578
  • 3
  • 10