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

BigQuery: added methods for getting keys, items and dict #4393

Merged
merged 15 commits into from
Nov 17, 2017
41 changes: 41 additions & 0 deletions bigquery/google/cloud/bigquery/table.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:

This comment was marked as spam.

This comment was marked as spam.

return default
return self._xxx_values[index]

def __getattr__(self, name):
value = self._xxx_field_to_index.get(name)
if value is None:
Expand Down
7 changes: 7 additions & 0 deletions bigquery/tests/unit/test_table.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down