diff --git a/bigquery/google/cloud/bigquery/table.py b/bigquery/google/cloud/bigquery/table.py index 191eba2f20ce..ce68e18ef735 100644 --- a/bigquery/google/cloud/bigquery/table.py +++ b/bigquery/google/cloud/bigquery/table.py @@ -785,6 +785,47 @@ def __init__(self, values, field_to_index): def values(self): return self._xxx_values + def keys(self): + """ + Return keys as of a dict: + >>> Row(('a', 'b'), {'x': 0, 'y': 1}).keys() + ['x', 'y'] + """ + keys = self._xxx_field_to_index.keys() + return keys + + def items(self): + """ + Return items as of a dict: + >>> Row(('a', 'b'), {'x': 0, 'y': 1}).items() + [('x', 'a'), ('y', 'b')] + """ + items = [ + (k, self._xxx_values[i]) + for k, i + in self._xxx_field_to_index.items() + ] + return items + + def get(self, key, default=None): + """ + Return value under specified key + Defaults to None or specified default + if key does not exist: + >>> Row(('a', 'b'), {'x': 0, 'y': 1}).get('x') + 'a' + >>> Row(('a', 'b'), {'x': 0, 'y': 1}).get('z') + None + >>> Row(('a', 'b'), {'x': 0, 'y': 1}).get('z', '') + '' + >>> Row(('a', 'b'), {'x': 0, 'y': 1}).get('z', default = '') + '' + """ + index = self._xxx_field_to_index.get(key) + if index is None: + return default + return self._xxx_values[index] + def __getattr__(self, name): value = self._xxx_field_to_index.get(name) if value is None: diff --git a/bigquery/tests/unit/test_table.py b/bigquery/tests/unit/test_table.py index 888974c3cdaf..49471f436be7 100644 --- a/bigquery/tests/unit/test_table.py +++ b/bigquery/tests/unit/test_table.py @@ -765,6 +765,13 @@ def test_row(self): self.assertEqual(row['c'], 3) self.assertEqual(len(row), 3) self.assertEqual(row.values(), VALUES) + self.assertEqual(set(row.keys()), set({'a': 1, 'b': 2, 'c': 3}.keys())) + self.assertEqual(set(row.items()), + set({'a': 1, 'b': 2, 'c': 3}.items())) + self.assertEqual(row.get('a'), 1) + self.assertEqual(row.get('d'), None) + self.assertEqual(row.get('d', ''), '') + self.assertEqual(row.get('d', default=''), '') self.assertEqual(repr(row), "Row((1, 2, 3), {'a': 0, 'b': 1, 'c': 2})") self.assertFalse(row != row)