In an existing PostgreSQL table, I would like to UPDATE several existing columns with values from a dictionary lookup (see dict below). Somewhat like described in this nice blog post. However, I can't figure out how to do that with a Python dictionary. Here comes the terrible pseudo-code:
d = {10:'chair', 11:'table', 12:'lamp',
20:'english ivy', 21:'peace lily', 22:'spider plant'}
curs.execute("""
UPDATE my_table t
SET furniture = %(t.furniture)s,
SET plant = %(t.plant)s""",
d)
The original table would look somewhat like this:
gid | furniture | plant
-----------------------
0 | 10 | 21
1 | 11 | 20
...
After the operation it should look like this:
gid | furniture | plant
-----------------------------
0 | chair | peace lily
1 | table | english ivy
...
Is this possible or will I have to loop through the table?
try this:
rows = (
{'gid': 10, 'furniture': 10, 'plant': 10},
{'gid': 20, 'furniture': 20, 'plant': 20}
)
cur.executemany(
'''
UPDATE myTable
SET
furniture = %(furniture)s,
plant = %(plant)s
WHERE
gid = %(gid)s
''',
rows
)
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