我目前有一个函数,它将字典作为输入并将数据库表中的所有列作为字典返回:
import sqlite3
def get_person_dict_from_dict(self):
database = "/Users/Mary/Documents/Database/{DB}.db".format(DB=self['db'])
conn = sqlite3.connect(database)
conn.row_factory = sqlite3.Row
c = conn.cursor()
sql_command = "SELECT * FROM {dbTableIn} WHERE Identifier = '{nameIn}' AND Day = {dateIn};".format(
dbTableIn=self['my_table'],
dateIn=self['date'],
nameIn=self['names'])
c.execute(sql_command)
r = c.fetchall()
result = [dict(row) for row in r]
dict_out = result[0]
return dict_out
inputDict = {"date" : '19891229',"names" : 'Mary', "db" :'MyDatabase', "my_table" :'Measurements'}
outputDict = get_person_dict_from_dict(inputDict)
这工作正常。但是,我该如何改进它:
1)我可以包含一个额外的参数,作为可变长度的列表/元组/字典,这样我就可以只提取我感兴趣的属性,而不是所有可用的指标。例如:
attributesWanted = ['Age', 'Height']
inputDict = {attributesWanted, "date" : '19891229',"names" : 'Mary', "db" :'MyDatabase', "my_table" :'Measurements'}
然而,例如,能够灵活地使用attributesWanted = ['Age', 'Height', 'ShoeSize'] if needed.
2)能够为多个人执行此操作。例如namesWanted = ['Mary', 'Joe']
最好能够使用单个字典作为函数的输入。我尝试过包含列表和元组,但遇到了诸如
TypeError:“元组”对象不是映射