Skip to content

Commit

Permalink
Created get_col method with tests and tutorial.rst update
Browse files Browse the repository at this point in the history
Useful when you have multiple columns with the same header
  • Loading branch information
mwalling committed Jul 11, 2011
1 parent cd5aa4f commit e74a8f4
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 1 deletion.
7 changes: 7 additions & 0 deletions docs/tutorial.rst
Expand Up @@ -146,6 +146,13 @@ To do so, we access the :class:`Dataset` as if it were a standard Python diction
>>> data['First Name']
['Kenneth', 'Bessie']

You can also access the column using its index. ::

>>> d.headers
['Last Name', 'First Name', 'Age']
>>> d.get_col(1)
['Kenneth', 'Bessie']

Let's find the average age. ::

>>> ages = data['Age']
Expand Down
7 changes: 6 additions & 1 deletion tablib/core.py
Expand Up @@ -175,7 +175,6 @@ def __getitem__(self, key):
else:
return [result.tuple for result in _results]


def __setitem__(self, key, value):
self._validate(value)
self._data[key] = Row(value)
Expand Down Expand Up @@ -695,6 +694,12 @@ def append_col(self, col, header=None):
self.rpush_col(col, header)


def get_col(self, index):
"""Returns the column from the :class:`Dataset` at the given index."""

return [row[index] for row in self._data]


# ----
# Misc
# ----
Expand Down
16 changes: 16 additions & 0 deletions test_tablib.py
Expand Up @@ -113,6 +113,22 @@ def test_header_slicing(self):
[self.john[2], self.george[2], self.tom[2]])


def test_get_col(self):
"""Verify getting columns by index"""

self.assertEqual(
self.founders.get_col(self.headers.index('first_name')),
[self.john[0], self.george[0], self.tom[0]])

self.assertEqual(
self.founders.get_col(self.headers.index('last_name')),
[self.john[1], self.george[1], self.tom[1]])

self.assertEqual(
self.founders.get_col(self.headers.index('gpa')),
[self.john[2], self.george[2], self.tom[2]])


def test_data_slicing(self):
"""Verify slicing by data."""

Expand Down

0 comments on commit e74a8f4

Please sign in to comment.