我正在尝试遍历通过json接收到的dict,并通过sqlalchemy将结果保存到数据库中。我一直保持字段名与dict中的键名相同。反复列出每个字段和dict似乎是重复的。但是当我尝试使用c.keys()之类的东西时,它就不起作用了。如果是这样的话,我可以: 对于c.keys()中的键: 客户.key=c[键]
但这行不通。我目前的代码是:
for c in response['Customers']:
customer = Customer()
customer.ID = c['ID']
customer.Name = c['Name']
customer.Currency = c['Currency']
customer.PaymentTerm = c['PaymentTerm']
customer.Discount = c['Discount']
customer.TaxRule = c['TaxRule']
customer.Carrier = c['Carrier']
session.add(customer)
session.commit()
您可以只使用unpack your dictionaries as arguments到{},前提是您没有重写与另一个答案完全相同的default constructor provided by Declarative;它从关键字参数设置属性:
您可以使用Python的^{} 函数,根据document:
因此,您可以将代码编写为:
在这里,我假设您在类中定义了与
dict
对象c
中的键相对应的所有属性。在相关问题 更多 >
编程相关推荐