Search code examples
pythonmysqlpython-3.6f-string

Query format with f-string


I have very big dictionary that I want to insert into MySQL table. The dictionary keys are the column names in the table. I'm constructing my query like this as of now:

bigd = {'k1':'v1', 'k2':10}
cols = str(bigd.keys()).strip('[]')
vals = str(bigd.values()).strip('[]')
query = "INSERT INTO table ({}) values ({})".format(cols,vals)
print query

Output:

"INSERT INTO table ('k2', 'k1') values (10, 'v1')"

And this works in Python2.7

But in Python 3.6 if I use string literals like this:

query = f"INSERT INTO table ({cols}) values ({vals})"
print(query)

It prints this:

"INSERT INTO table (dict_keys(['k1', 'k2'])) values (dict_values(['v1', 10]))"

Any tips?


Solution

  • For your curiosity, you should realize that you've cast these to str, getting the representation of dict_keys/values to be inserted into the f-string.

    You could just cast to tuples and then insert:

    cols = tuple(bigd.keys())
    vals = tuple(bigd.values())
    q = f"INSERT INTO table {cols} values {vals}"
    

    but, as the comment notes, this isn't a safe approach.