1

I want to fill NULL values of a column in table by iterating key and value of the dictionary.

My table is like below

item_name item_value
A NULL
B NULL
C NULL
D NULL

and my dictionary is like below

dict = {'A': '%', 'B': 'COUNT', 'C': 'COUN', 'D': 'PSI'}

What I'm trying now is

value = (value, key)
for key, value in dict.items():
  cursor.execute("INSERT INTO table(item_value) values(%s) where item_name =(%s)", value)
conn.commit()
cursor.close()

the output I want is

item_name item_value
A %
B COUNT
C COUN
D PSI

Would this code accomplish what I want to do?

1 Answer 1

2

Looks like you are trying to update the row in the table.

Use UPDATE query instead of INSERT .

You can try this code :

for key,value in dict_name.items():
    cursor.execute("UPDATE table_name SET item_value = {} where item_name = '{}';".format(value,key))
conn.commit()
cursor.close()
Sign up to request clarification or add additional context in comments.

2 Comments

I want to replace the null values of item_value column with values of dict, can I do [for key,value in dict_name.items(): cursor.execute("UPDATE table_name SET item_value = {} where item_name = '{}';".format(value,key)) conn.commit() cursor.close()]
Yes that would work.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.