所以我要添加和更新python字典。目前它看起来很难看,难以阅读,是否有更好的方法做同样的事情?
if not transaction_id in self.transaction_log:
self.transaction_log[transaction_id] = {
'gross_total': 0,
'net_total': 0,
'qty_total': 0,
'tax_total': 0
}
self.transaction_log[transaction_id]['products'] = {}
# create a list of dics to be reused in
# other class methods
self.transaction_log[transaction_id].update({
'transaction_id': transaction_id,
'transaction_time': transaction_datetime,
'location_id': location_id,
'till_id': till_id,
'employee_id': employee_id,
})
self.transaction_log[transaction_id]['products'][product_id] = {
'gross': gross,
'net': net,
'tax': tax,
'qty': qty
}
self.transaction_log[transaction_id]['gross_total'] += gross
self.transaction_log[transaction_id]['net_total'] += net
self.transaction_log[transaction_id]['qty_total'] += tax
self.transaction_log[transaction_id]['tax_total'] += qty
答案 0 :(得分:2)
这可能更适合codereview.stackexchange.com :
transaction = self.transaction_log.setdefault(transaction_id, { 'products': {} })
# create a list of dics to be reused in
# other class methods
transaction.update({
'gross_total': transaction.get('gross_total', 0) + gross,
'net_total': transaction.get('net_total', 0) + net,
'qty_total': transaction.get('qty_total', 0) + qty,
'tax_total': transaction.get('tax_total', 0) + tax,
'transaction_id': transaction_id,
'transaction_time': transaction_datetime,
'location_id': location_id,
'till_id': till_id,
'employee_id': employee_id
})
transaction['products'].update({
product_id: {
'gross': gross,
'net': net,
'tax': tax,
'qty': qty
}
})
此外,您似乎已撤消qty
和tax