Insert Dictionary Sqlite3 (python)
New to sqlite and having trouble with the syntax. I need to iterate through each key of a dictionary and insert dict[key] into the column with the same name as the dictionary key.
Solution 1:
You can use named parameters for all your insert:
cur.execute("INSERT INTO GAMES (key1, key2, key3, key4) VALUES (:key1, :key2, :key3, :key4)",
merged_dict)
This will take parameters by name from a dictionary, but those keys do have to exist. To support keys that may not exist (defaulting them to NULL
instead, use a defaultdict
object that will use None
for missing keys:
from collections import defaultdict
params = defaultdict(lambda: None, merged_dict)
cur.execute("INSERT INTO GAMES (key1, key2, key3, key4) VALUES (:key1, :key2, :key3, :key4)",
params)
Post a Comment for "Insert Dictionary Sqlite3 (python)"