MCPcopy Create free account
hub / github.com/ActiveState/code / Table

Class Table

recipes/Python/334621_List_Dictionaries_Memory/recipe-334621.py:4–38  ·  view source on GitHub ↗

A structure which implements a list of dict's.

Source from the content-addressed store, hash-verified

2import types
3
4class Table(object):
5 """A structure which implements a list of dict's."""
6 def __init__(self, *args):
7 self.columns = args
8 self.rows = []
9
10 def _createRow(self, k,v):
11 return dict(zip(k, v))
12
13 def append(self, row):
14 if type(row) == types.DictType:
15 row = [row[x] for x in self.columns]
16 row = tuple(row)
17 if len(row) != len(self.columns):
18 raise TypeError, 'Row must contain %d elements.' % len(self.columns)
19 self.rows.append(row)
20
21 def __iter__(self):
22 for row in self.rows:
23 yield self._createRow(self.columns, row)
24
25 def __getitem__(self, i):
26 return self._createRow(self.columns, self.rows[i])
27
28 def __setitem__(self, i, row):
29 if type(row) == types.DictType:
30 row = [row[x] for x in self.columns]
31 row = tuple(row)
32 if len(row) != len(self.columns):
33 raise TypeError, 'Row must contain %d elements.' % len(self.columns)
34 self.rows[i] = row
35
36 def __repr__(self):
37 return ("<" + self.__class__.__name__ + " object at 0x" + str(id(self))
38 + " " + str(self.columns) + ", %d rows.>" % len(self.rows))
39
40
41

Callers 1

recipe-334621.pyFile · 0.70

Calls

no outgoing calls

Tested by

no test coverage detected