Skip to content

Commit

Permalink
Fixes #24 - Add get() row method to Dataset
Browse files Browse the repository at this point in the history
  • Loading branch information
yoonthegoon authored Aug 2, 2023
1 parent d4e68c6 commit 98b8c53
Show file tree
Hide file tree
Showing 4 changed files with 32 additions and 0 deletions.
1 change: 1 addition & 0 deletions AUTHORS
Original file line number Diff line number Diff line change
Expand Up @@ -32,3 +32,4 @@ Here is a list of past and present much-appreciated contributors:
Tommy Anthony
Tsuyoshi Hombashi
Tushar Makkar
Yunis Yilmaz
6 changes: 6 additions & 0 deletions docs/tutorial.rst
Original file line number Diff line number Diff line change
Expand Up @@ -167,7 +167,13 @@ You can slice and dice your data, just like a standard Python list. ::

>>> data[0]
('Kenneth', 'Reitz', 22)
>>> data[0:2]
[('Kenneth', 'Reitz', 22), ('Bessie', 'Monke', 20)]

You can also access a row using its index without slicing. ::

>>> data.get(0)
('Kenneth', 'Reitz', 22)

If we had a set of data consisting of thousands of rows,
it could be useful to get a list of values in a column.
Expand Down
8 changes: 8 additions & 0 deletions src/tablib/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -501,6 +501,14 @@ def pop(self):

return self.rpop()

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

if isinstance(index, int):
return self[index]

raise TypeError('Row indices must be integers.')

# -------
# Columns
# -------
Expand Down
17 changes: 17 additions & 0 deletions tests/test_tablib.py
Original file line number Diff line number Diff line change
Expand Up @@ -195,6 +195,23 @@ def test_header_slicing(self):
self.assertEqual(self.founders['gpa'],
[self.john[2], self.george[2], self.tom[2]])

def test_get(self):
"""Verify getting rows by index"""

self.assertEqual(self.founders.get(0), self.john)
self.assertEqual(self.founders.get(1), self.george)
self.assertEqual(self.founders.get(2), self.tom)

self.assertEqual(self.founders.get(-1), self.tom)
self.assertEqual(self.founders.get(-2), self.george)
self.assertEqual(self.founders.get(-3), self.john)

with self.assertRaises(IndexError):
self.founders.get(3)

with self.assertRaises(TypeError):
self.founders.get('first_name')

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

Expand Down

0 comments on commit 98b8c53

Please sign in to comment.