I've been trying to figure out how to pass a list of values as an individual parameter for pydblite.insert(*args). Each value from the list 'temp' and 'keys' must be an individual parameter for both the .insert() and .create() function respectively.
def copyToMemory(self, table, items):
db = Base(table + ".pdl")
if not (db.exists()):
keys = ""
for key, val in items[0].items(): keys += key + ', '
#db.create(keys)
db.open()
for i in items:
temp = []
for val in i.itervalues():
temp += val
#db.insert(temp)
For the db.create()
, construct a list of the keys and pass them as unpacked arguments like this:
db.create(*items[0].keys())
Since items
is a list of dictionaries, you can simply use dict.keys()
to get a list of the keys using the first item in the list. This list of keys is then unpacked to pass positional arguments to the create()
function. For reference see * in function calls.
Because dict.keys()
is unordered, the above assumes that you do not particularly care about the order of the fields in the table.
For db.insert()
you can pass an unpacked dictionary using **
:
for item in items:
db.insert(**item)
See ** in function calls. This will pass the arguments to the function as keyword arguments. Note that the order does not matter - the fields in the table will be properly associated with the corresponding item from the dictionary.