将BigQuery行转换为以第一列为键的字典



我使用的是BigQuery Python API,我有一个query_job,它返回2 x n行。第一列中的值保证是唯一的。我想将结果转换为Python字典,其中第一列的值将成为字典键,第二列的值成为字典值。当然,我可以在每一行做循环;但我只是想知道是否还有更优雅的(读作:快捷方式(解决方案。

您可以直接将查询返回的对象转换为dict:

from google.cloud import bigquery
# Construct a BigQuery client object.
client = bigquery.Client()
query = """
SELECT id, name
FROM `project_id.dataset_id.table_id`
ORDER BY id
LIMIT 20
"""
query_job = client.query(query)  # Make an API request.
result_dict = dict(query_job)

这里假设id列具有将用作键的唯一值。

试试这个:

from google.cloud import bigquery
# Construct a BigQuery client object.
client = bigquery.Client()
query = """
SELECT id, name
FROM `project_id.dataset_id.table_id`
ORDER BY id
LIMIT 20
"""
query_job = client.query(query)  # Make an API request.
for row in query_job:
print(dict(row.items()))

最新更新