1

anyone can tell me how can I solve this please; I have this:

dct = {
"A": ['None', 'None', 'None'],
"B" : ['None', 'None', 'None'] ,
"C": ['None', 'None', 'None'] ,
"D": ['None', 'None', 'None']

}

and I am getting this: enter image description here

but, i want get this format: enter image description here

any ideas please ?

this is my code:

def pretty_table(dct):
  table = PrettyTable()
  for c in dct.keys():
     table.add_column(c, [])
  table.add_row([dct.get(c, "") for c in dct.keys()])
  print(table)
Elhabib
  • 141
  • 2
  • 10

2 Answers2

3

You can insert each list in the cell as a string composed by the elements joined through a newline:

def pretty_table(dct):
  table = PrettyTable()
  for c in dct.keys():
     table.add_column(c, [])
  table.add_row(['\n'.join(dct[c]) for c in dct.keys()])
  print(table)

This will be the output:

+------+------+------+------+
|  A   |  B   |  C   |  D   |
+------+------+------+------+
| None | None | None | None |
| None | None | None | None |
| None | None | None | None |
+------+------+------+------+
Flavio
  • 121
  • 6
0

You could also try to use zip():

def pretty_table(dct):
    table = PrettyTable(dct.keys())
    table.add_rows(zip(*dct.values()))
    print(table)
JcGKitten
  • 3
  • 3
  • Can you explain your code? – TheTridentGuy supports Ukraine Jun 06 '23 at 06:06
  • Hey, yes of course: `table = PrettyTable(dct.keys())` takes the keys of the dictonary: A,B,C and D and initializes a PrettyTable with them as column names. `table.add_rows(zip(*dct.values()))` : `dct.values() ` returns all dictonary values in a list, so we got a list of lists: `[ [None, None, None], [None, None, None],...]`. The `*` takes each element of that list an uses it as a argument for the zip function. In this case the zip function gets four times the list `[None, None, None]` and combines the first element of each list into a tuple, then the second and so on. This are the rows then. – JcGKitten Jun 06 '23 at 13:49