繁体   English   中英

在字典的字典中更新特定字典的键

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM