Search code examples
pythonpython-3.xtabulate

Formatting API List with for loop in a Table


I want to output a list I get from the API in a table so it looks nicer. The data from the API is returned with a for loop. My problem now is that I don't know how to get it that the header isn't looped every time.

for Example:

And i want one header and the rest under the header

I have managed with some instructions from here that the data will be displayed with "Tabulate" at all in a table. However, the "header" will be inserted at each run again.

head = ["Datum", "Username", "License Server", "Feature Name", "Max. Usage", "Hours Used", "Max Used", "Hours Borrowed", "Max Borrowed"]

for item in (data['data'])
   if item['un'] == tecNo:
      print(tabulate([[item['fud'], item['un'], str(item['lsn']), str(item['fns']), str(item['musage']), str(item['hu']), str(item['mu']), str(item['hb']), str(item['mb'])]],headers=head, tablefmt="grid"))```


  [1]: https://i.sstatic.net/ZHODf.png
  [2]: https://i.sstatic.net/pNci2.png

Solution

  • You need to put the items in a 2d array, then call tabulate at the end.

    table = []
    for item in (data['data'])
       if item['un'] == tecNo:
          table.append([
              item['fud'], 
              item['un'], 
              str(item['lsn']), 
              str(item['fns']), 
              str(item['musage']), 
              str(item['hu']), 
              str(item['mu']), 
              str(item['hb']), 
              str(item['mb'])
          ])
    tabulate(table, headers=head)