Skip to content

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

Open
@Pantsworth

Description

@Pantsworth

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or request

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions