Home > Software engineering >  How to use f strings in BigQuery results variable in Python?
How to use f strings in BigQuery results variable in Python?

Time:10-12

I am trying to create a script that iterates through a list, and runs sql queries using the list values as part of the WHERE condition. The SQL service in question is GBQ, and I am running the scripting process through python.

I have the script working as intended, bar saving the results to a dynamic variable, in which I had intended to use f strings. My code is as follows (edited for privacy reasons):

import pandas_gbq
import pandas as pd

list = ["1", "2"]
for i in list:
query = f''' SELECT *, FROM TABLEA, WHERE CONDITION LIKE '%{i}%' GROUP BY 1'''
results = pandas_gbq.read_gbq(query, project_id = 'privacyreasons')

However, when I try to implement an f string in the naming of the results variable, utilising the following code:

f' results{i}' = pandas_gbq.read_gbq(query, project_id = 'privacyreasons'')

I receive the following error:

SyntaxError: cannot assign to f-string expression

Any help in dynamically naming the results variable to individually store the query results per {i}? Currently, the results variable just gets overwritten with the last run of the query utilising the last {i} value within the query.

Thanks!

CodePudding user response:

This question and error are unrelated to BigQuery. You cannot use f-strings that way; this short example demonstrates the same issue:

for i in [1, 2]:
    f'result_{i}' = i

leads to

    f'result_{i}' = i
    ^
SyntaxError: cannot assign to f-string expression

Instead, you could store the results in a dictionary:

results = {}
for i in [1, 2]:
    results[f'result_{i}'] = i

If you really want to dynamically create variables, which is rarely a good idea, you can use globals():

for i in [1, 2]:
    globals()[f'result_{i}'] = i

print(result_1)
print(result_2)

Output:

1
2
  • Related