Issue #27 duplicate

List of dicts formatting

Kristof Speeckaert
created an issue

I noticed an issue with the formatting of a list of dict, as show by the sample statements above.

x = [dict(x=1, y=2), dict(x=3, y=4)]

Trying with headers=keys:

print(tabulate(x, headers='keys', tablefmt='pipe'))

Result:

| 0   | 1   |
|:----|:----|
| x   | y   |
| x   | y   |

Trying with headers=firstrow

print(tabulate(x, headers='firstrow', tablefmt='pipe'))

Result (the header is correct, but the contents are not):

| x   | y   |
|:----|:----|
| x   | y   |

The only way I can get tabulate to print the correct output is by doing as follows:

tabulate([item.values() for item in x],
              tablefmt='pipe',
              headers=x[0].keys())

Result:

|   x |   y |
|----:|----:|
|   1 |   2 |
|   3 |   4 |

However, I know that this last statement might generate output where the headers and contents don't match (issue 23).

Comments (3)

  1. Sergey Astanin repo owner

    Hi Kristof,

    printing lists of dicts was implemented and improved after the last release 0.7.2. See issue #21.

    Current git master (and future, yet to be release 0.7.3 version) formats the list this way:

    In [3]: print tabulate(x, "keys", "pipe")
    |   y |   x |
    |----:|----:|
    |   2 |   1 |
    |   4 |   3 |
    
    In [4]: print tabulate(x, "firstrow", "pipe")
    |   2 |   1 |
    |----:|----:|
    |   4 |   3 |
    

    Hopefully, you'll find this feature satisfactory.

  2. Kristof Speeckaert reporter

    You're absolutely right, Sergey. I had installed version 0.7.3, pulling it from Git, but 0.7.2 must've still been in the interactive console's memory after I installed it. I just retried my example, and it works just fine now.

    Sorry for the confusion.

  3. Log in to comment