Search code examples
pythonoutputoutput-formatting

python Tabulate library: TypeError: zip_longest argument #1 must support iteration


I have this dictionary: {'id': 1, 'inner': {'test1': 1, 'test2': 2}} which I want to tabulate, but I get the following exception:

>>> from tabulate import tabulate
>>> d = {'id': 1, 'inner': {'test1': 1, 'test2': 2}}
>>> tabulate(d)

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File ".../env/lib/python3.6/site-packages/tabulate.py", line 1529, in tabulate
    tabular_data, headers, showindex=showindex
  File ".../env/lib/python3.6/site-packages/tabulate.py", line 1089, in _normalize_tabular_data
    izip_longest(*tabular_data.values())
TypeError: zip_longest argument #1 must support iteration

I can't understand why I'm getting this and how can I make sure this won't happen again. My dictionary is my server answer and the schema of it could easily change and this formatting kinda should support everything(!), so I'm looking for a general solution. I know that not every schema makes sense being formatted as a table, but that's the user's choice.

versions: tabulate=0.8.9 python=3.6.9


Solution

  • According to the doc:

    The following tabular data types are supported:
    
      1.list of lists or another iterable of iterables
      2.list or another iterable of dicts (keys as columns)
      3.dict of iterables (keys as columns)
      4.two-dimensional NumPy array
      5.NumPy record arrays (names as columns)
      6.pandas.DataFrame
    

    if you want to use the dictionary, it must be dict of iterable, which means your example would be

    {'id': [1], 'inner': {'test1': [1], 'test2': [2]}}