Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

code:

schema = [{"name": "fb_table_1", "dimension": "department", "metrics": ["headcount"]},
          {"name": "fb_table_2", "dimension": "area", "metrics": ["sale"]},
          {"name": "fb_table_3", "dimension": "product", "metrics": ["quantity", "revenue"]}]

template = f"select date, '{table["dimension"]}', {table['dimension']}, '{metric}', {metric} from {table['name']}"
sql_2 = " union ".join([template for table in schema for metric in table["metrics"]])
print(sql_2)

get following errors:

template = f"select date, '{table["dimension"]}', {table['dimension']}, '{metric}', {metric} from {table['name']}"
                                               ^
SyntaxError: invalid syntax

Is that caused by the nested single/double quotations?

update: when I change to

template = f"select date, '{table['dimension']}', {table['dimension']}, '{metric}', {metric} from {table['name']}"

I get another error:

NameError: name 'table' is not defined

what's the cause of this one?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
297 views
Welcome To Ask or Share your Answers For Others

1 Answer

It might be the nested quotations, in which case you should just replace the double-quotes at the beginning and ending with ''' - this is still a valid string literal in Python.

The other issue is that your f-string depends on variables not yet declared. In this problem, you would perhaps like to encapsulate this in a function that takes table and metric and returns the formatted string.

Consider this implementation -

schema = [{"name": "fb_table_1", "dimension": "department", "metrics": ["headcount"]},
          {"name": "fb_table_2", "dimension": "area", "metrics": ["sale"]},
          {"name": "fb_table_3", "dimension": "product", "metrics": ["quantity", "revenue"]}]

def get_required_string(table, metric):
    template = f'''
    select date, '{table["dimension"]}', {table['dimension']}, '{metric}', {metric} from {table['name']}
    '''
    return template

sql_2 = " union ".join([get_required_string(table, metric) for table in schema for metric in table["metrics"]])
print(sql_2)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...