Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert dictionary to a string and separate by coma each key-value pair

Tags:

python

mysql

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'
like image 558
Vor Avatar asked Dec 06 '22 06:12

Vor


1 Answers

Something like this?

>>> ", ".join(["=".join([key, str(val)]) for key, val in data.items()])
'foo=1, bar=2'
like image 140
Sukrit Kalra Avatar answered Jan 01 '23 10:01

Sukrit Kalra