0

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. If it makes any difference, dict['Url'] contains the primary key, and all the rows are already created.

So far I think I've witnessed every possible OperationalError.

for key in merged_dict:
    cur.execute("INSERT INTO Games VALUES (?,?)", (key, merged_dict[key]))

1 Answer 1

3

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)
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you. Really thought there'd be an easier way to do stuff like this in py/sql...

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.