-
Notifications
You must be signed in to change notification settings - Fork 5
/
Table.py
51 lines (40 loc) · 1.32 KB
/
Table.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
from collections import namedtuple
import pprint
import csv
Metadata = namedtuple("Metadata", "num_cols num_entries")
class Table:
def __init__(self, data):
"""
Stores a given table as a dictionary. The keys are the headings and the
values are the data, represented as lists.
"""
self.table_data = data
def get_metadata(self):
"""
Returns a Metadata object that contains the number of columns
and the total number of entries.
"""
col_headings = self.table_data.keys()
num_cols = len(col_headings)
num_entries = 0
for heading in col_headings:
num_entries += len(self.table_data[heading])
return Metadata(
num_cols = num_cols,
num_entries = num_entries
)
def show_table(self):
"""
Prints a formatted table to the command line using pprint
"""
pprint.pprint(self.table_data, width=1)
def save_table(self, name):
"""
Saves a table to csv format under the given file name.
File name should omit the extension.
"""
fname = name + ".csv"
with open(fname, 'wb') as outf:
w = csv.writer(outf, dialect="excel")
li = self.table_data.values()
w.writerows(li)