Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 448
oikonomiyaki Avatar asked Oct 30 '25 17:10

oikonomiyaki


1 Answers

Try this:

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()))
like image 188
JavDomGom Avatar answered Nov 01 '25 08:11

JavDomGom



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!