Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Get row method #557

Merged
merged 6 commits into from
Aug 2, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
Loading