astanin / python-tabulate

Pretty-print tabular data in Python, a library and a command-line utility. Repository migrated from bitbucket.org/astanin/python-tabulate.
https://pypi.org/project/tabulate/
MIT License
2.17k stars 164 forks source link

Feature Request: Support a list of headers when passing a list of dicts #36

Open Pantsworth opened 4 years ago

Pantsworth commented 4 years ago

This is an awesome library!

I have a use case that's not quite covered right now. I often have a giant list of dictionaries, where each dictionary has about ~400 key:value pairs.

(Ex. I want it to ignore the data under ignore_this_key and and_this_one)

tasks = [
        {'id': 1, 'name': 1, 'ignore_this_key': 1, 'and_this_one': 1},
        {'id': 2, 'name': 2, 'ignore_this_key': 2, 'and_this_one': 2}
    ]

What I'd like to be able to do is pass a list or dictionary of headers and get an output that shows only the keys I specified in the headers (if I include all the keys as columns, it's way too beefy for my terminal)

Ex.

  id    name
   1       1
   2       2

But right now, if I call tabulate.tabulate(tasks, headers={'id': 'id', 'name': 'name'}), I get:

  ignore_this_key    and_this_one    id    name
                1               1     1       1
                2               2     2       2

I wrote a little function that does what I want, but it would be more elegant if it was in tabulate itself:

import tabulate

tasks = [
        {'id': 1, 'name': 1, 'ignore_this_key': 1, 'and_this_one': 1},
        {'id': 2, 'name': 2, 'ignore_this_key': 2, 'and_this_one': 2}
    ]

def task_table(task_data, headers):
    result_data = [{k: t[k] for k in t if k in headers} for t in task_data]
    if not isinstance(headers, dict):
        headers = {h: h for h in headers}
    return tabulate.tabulate(result_data, headers=headers)

print(task_table(tasks, ['id', 'name']))

If this seems reasonable, I'll take a crack at a PR for it 😄. If there's already a way I can do this, apologies.

jhulance commented 4 months ago

The suggested change works for me when I faced this issue with this module. I have a list of dictionaries, and I want the column headers in a specific order, not the order given by .keys() on whatever happens to be the first item.