I'm trying to write a simple function to update MySQL table from python dictionary:
data = {'foo':1, 'bar':2}
table = 'mytable'
pk = 'mypk'
pk_value = 1
sql = ''
sql += 'UPDATE ' + table
sql += 'SET ' + convert_dict_to_str(data)
sql += 'WHERE ' + pk
sql += ' = ' + pk_value
sql += ';'
def convert_dict_to_str(data):
result = ''
for key in data:
result += "{key} = {value}".format(key=key, value=data[key])
return result
print convert_dict_to_str(data)
But I got stuck on how to convert dict into "key = value, key = value"
?
In my example the desired output should be:
'foo = 1, bar = 2'
Something like this?
>>> ", ".join(["=".join([key, str(val)]) for key, val in data.items()])
'foo=1, bar=2'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With