Python 3.x 更新python字典值
因此,我正在添加和更新python字典。目前它看起来很难看,很难阅读,有没有更好的方法来做同样的事情Python 3.x 更新python字典值,python-3.x,Python 3.x,因此,我正在添加和更新python字典。目前它看起来很难看,很难阅读,有没有更好的方法来做同样的事情 if not transaction_id in self.transaction_log: self.transaction_log[transaction_id] = { 'gross_total': 0, 'net_total': 0, 'qty_tota
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
这可能更适合于:
另外,看起来您颠倒了
数量
和税务
我们可以为这个代码提供更多的上下文吗?我建议在代码片段的开头引用self.transaction\u log[transaction\u id]
,以便将其作为局部变量引用,然后设置self.transaction\u log[transaction\u id]['products']={}
但是可以在上面的定义中添加'products':{}
。不幸的是dict.update
不能递归工作,因此如果'products'
已经存在,它将被完全覆盖,删除可能存在的任何其他product\u id
条目。good catch@tadhgmandald Jensen。答案已经更新了。我还注意到-因为您使用的是transaction.get('gross\u total',0)
所以不需要在上面定义它,这样您就可以将第一个语句简化为transaction=self.transaction\u log.get(transaction\u id,{'products':{})
或者更好的方法是使用setdefault
而不是get
,这样你就不需要在底部重新分配它了。你是天才@TadhgMcDonald Jensen。现在编辑它
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
}
})