所以我添加和更新一個python字典。目前它看起來非常難看,很難閱讀,有沒有更好的方法來做同樣的事情?更新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
我們可能對這個碼多一點背景?簡單地重構已經工作的代碼通常在http://codereview.stackexchange.com上處理。 –
我建議的兩件事是在代碼片段的開始處引用'self.transaction_log [transaction_id]',以便引用它作爲一個局部變量,並且你可以在上面的定義中設置'self.transaction_log [transaction_id] ['products'] = {}',但是可以添加''products':{}'。 –