2016-08-30 95 views
1

所以我添加和更新一個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 
+1

我們可能對這個碼多一點背景?簡單地重構已經工作的代碼通常在http://codereview.stackexchange.com上處理。 –

+1

我建議的兩件事是在代碼片段的開始處引用'self.transaction_log [transaction_id]',以便引用它作爲一個局部變量,並且你可以在上面的定義中設置'self.transaction_log [transaction_id] ['products'] = {}',但是可以添加''products':{}'。 –

回答

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 
    } 
}) 

此外,它看起來像你逆轉qtytax

+1

不幸的是'dict.update'不能遞歸地工作,所以如果''products''已經存在,它將被完全覆蓋,刪除可能存在的其他'product_id'條目。 –

+0

好抓@TadhgMcDonald-Jensen。答案已經更新。 – Patrick

+1

我也注意到了 - 因爲你正在使用'transaction.get('gross_total',0)',所以不需要在上面定義它,所以你可以簡化第一條語句爲'transaction = self.transaction_log.get (transaction_id,{'products':{}})'或者更好的是使用'setdefault'而不是'get',所以你不需要在底部重新分配它。 –