'Converting BigQuery rows into a dictionary with the first column as the key

I am using BigQuery Python API, and I have a query_job that returns a 2 x n rows. The values in the first column is guaranteed to be unique. I want to convert the result into a Python dictionary, where the values in the first column will become the dictionary keys and the values on the second column become the dictionary values. I can do loop on each row, of course; but I just wonder if there is more elegant (read: shortcut) solution.



Solution 1:[1]

You can directly convert the object returned from your query to a 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)

It is assumed here that the id column has unique values that will serve as keys.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 itroulli