[英]update key of specific dict in dict of dicts
我正在創建字典字典,然后嘗試使用 for 循環更新特定鍵。 但是,所有密鑰都在更新。
代碼如下:
transactions = Transaction.objects.all()
unique_sellers = ['A002638841D', 'A09876543456']
seller_summary={}
summary = {
'total_loan_amount': 0,
'gross_incentive': 0,
}
for each in unique_sellers:
seller_summary[each] = summary
seller_summary[each]['total_loan_amount'] = transactions.filter(channel_seller__pin_no = each).aggregate(total_loan_amount=Sum('loan_amount'))['total_loan_amount']
print(seller_summary)
A002638841D 的A002638841D
是 1500
A09876543456 的A09876543456
是 2000
我的期望是 output 的print(seller_summary)
應該是{'A002638841D': {'total_loan_amount': 1500, 'gross_incentive': 0,}, 'A09876543456': { 'total_loan_amount': 2000, 'gross_incentive': 0,}}
但是,我得到 output,如下我的期望是{'A002638841D': {'total_loan_amount': 2000, 'gross_incentive': 0,}, 'A09876543456': { 'total_loan_amount': 2000, 'gross_incentive': 0,}}
total_loan_amount 是字典分別更新為 2000 而不是 1500 和 2000
當您為每個鍵分配summary
字典時,摘要是原始摘要變量的引用,因此您更新了相同的字典兩次。 也許你可以試試
transactions = Transaction.objects.all()
unique_sellers = ['A002638841D', 'A09876543456']
seller_summary={}
def get_summary(): # create a new reference each time instead of using the same one
return {
'total_loan_amount': 0,
'gross_incentive': 0,
}
for each in unique_sellers:
seller_summary[each] = get_summary()
# EDIT: Or like said in comments, simply create the dict reference here :
# seller_summary[each] = { 'total_loan_amount': 0, 'gross_incentive': 0,}
seller_summary[each]['total_loan_amount'] = transactions.filter(channel_seller__pin_no = each).aggregate(total_loan_amount=Sum('loan_amount'))['total_loan_amount']
print(seller_summary)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.