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?
wim
369k114 gold badges682 silver badges822 bronze badges
asked Dec 18, 2016 at 16:34
Mohammad Yusuf
17.1k12 gold badges60 silver badges88 bronze badges
1 Answer 1
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.
answered Dec 18, 2016 at 16:47
Dimitris Fasarakis Hilliard
162k35 gold badges282 silver badges265 bronze badges
Sign up to request clarification or add additional context in comments.
2 Comments
indianwebdevil
I tried this ` INSERT INTO user ('id', 'field2') values ('1', 'value2') ` - there is single quotes surrounding field names, and it throws the syntax error. ` syntax error at or near "'id'" LINE 1: INSERT INTO user ('id', `.
indianwebdevil
btw, its a cool construct :)
default
','.join(map(repr, whatever))is neater and continues to work.