Skip to content

Commit d18dc9b

Browse files
committed
Improved how dictionaries are handled
They are now dealt within in the same way as the tabulate package which assumes the keys are column labels and the values are iterables containing the column values.
1 parent 3a0734c commit d18dc9b

File tree

2 files changed

+8
-2
lines changed

2 files changed

+8
-2
lines changed

examples/data_types.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -47,8 +47,7 @@
4747
print(iterable_of_dicts)
4848
print(tf.generate_table(iterable_of_dicts))
4949

50-
dict_of_iterables = {(1, 2, 3, 4): 'a',
51-
(5, 6, 7, 8): 'b'}
50+
dict_of_iterables = d
5251
print("Data type: dict of iterables (dict keys iterated through as rows where each key must be a hashable iterable)")
5352
print(dict_of_iterables)
5453
print(tf.generate_table(dict_of_iterables))

tableformatter.py

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
"""
55
import abc
66
import enum
7+
import itertools
78
import re
89
import textwrap as textw
910
from typing import List, Iterable, Optional, Tuple, Union, Callable
@@ -615,6 +616,12 @@ def generate_table(rows: Iterable[Union[Iterable, object]],
615616
:param row_tagger: decorator function to apply per-row options
616617
:return: formatted string containing the table
617618
"""
619+
# If a dictionary is passed in, then treat keys as column headers and values as column values
620+
if isinstance(rows, dict):
621+
if not columns:
622+
columns = rows.keys()
623+
rows = list(itertools.zip_longest(*rows.values())) # columns have to be transposed
624+
618625
# Extract column headers if this is a NumPy record array and columns weren't specified
619626
if not columns:
620627
try:

0 commit comments

Comments
 (0)