在 pydblite 中将列表作为参数传递
Passing list as argument in pydblite
我一直在尝试弄清楚如何将值列表作为 pydblite.insert(*args) 的单独参数传递。列表 'temp' 和 'keys' 中的每个值必须分别是 .insert() 和 .create() 函数的单独参数。
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)
对于 db.create()
,构造一个键列表并将它们作为解压缩的参数传递,如下所示:
db.create(*items[0].keys())
由于 items
是一个字典列表,您可以简单地使用 dict.keys()
来使用列表中的第一项来获取键列表。然后解压缩此键列表以将 positional 参数传递给 create()
函数。有关参考,请参阅 * in function calls。
因为dict.keys()
是无序的,上面假设你并不特别关心table中字段的顺序。
对于 db.insert()
你可以使用 **
:
传递一个解压的字典
for item in items:
db.insert(**item)
参见 ** in function calls。这会将参数作为关键字参数传递给函数。请注意,顺序无关紧要 - table 中的字段将与字典中的相应项目正确关联。
我一直在尝试弄清楚如何将值列表作为 pydblite.insert(*args) 的单独参数传递。列表 'temp' 和 'keys' 中的每个值必须分别是 .insert() 和 .create() 函数的单独参数。
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)
对于 db.create()
,构造一个键列表并将它们作为解压缩的参数传递,如下所示:
db.create(*items[0].keys())
由于 items
是一个字典列表,您可以简单地使用 dict.keys()
来使用列表中的第一项来获取键列表。然后解压缩此键列表以将 positional 参数传递给 create()
函数。有关参考,请参阅 * in function calls。
因为dict.keys()
是无序的,上面假设你并不特别关心table中字段的顺序。
对于 db.insert()
你可以使用 **
:
for item in items:
db.insert(**item)
参见 ** in function calls。这会将参数作为关键字参数传递给函数。请注意,顺序无关紧要 - table 中的字段将与字典中的相应项目正确关联。