diff --git a/AUTHORS b/AUTHORS index b040803a..8b2336b5 100644 --- a/AUTHORS +++ b/AUTHORS @@ -32,3 +32,4 @@ Here is a list of past and present much-appreciated contributors: Tommy Anthony Tsuyoshi Hombashi Tushar Makkar + Yunis Yilmaz diff --git a/docs/tutorial.rst b/docs/tutorial.rst index 23f48280..e5cd12bc 100644 --- a/docs/tutorial.rst +++ b/docs/tutorial.rst @@ -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. diff --git a/src/tablib/core.py b/src/tablib/core.py index 61fce9d2..252da78e 100644 --- a/src/tablib/core.py +++ b/src/tablib/core.py @@ -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 # ------- diff --git a/tests/test_tablib.py b/tests/test_tablib.py index 0837a765..03ac58b2 100755 --- a/tests/test_tablib.py +++ b/tests/test_tablib.py @@ -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"""