简体   繁体   English

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

[英]update key of specific dict in dict of dicts

I'm creating a dictionary of dictionaries and then trying to update a specific key using for loop.我正在创建字典字典,然后尝试使用 for 循环更新特定键。 however, all keys are getting updated.但是,所有密钥都在更新。

code is as follows:代码如下:

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)

total_loan_amount for A002638841D is 1500 A002638841D 的A002638841D是 1500

total_loan_amount for A09876543456 is 2000 A09876543456 的A09876543456是 2000

my expectations is output of print(seller_summary) should be {'A002638841D': {'total_loan_amount': 1500, 'gross_incentive': 0,}, 'A09876543456': { 'total_loan_amount': 2000, 'gross_incentive': 0,}}我的期望是 output 的print(seller_summary)应该是{'A002638841D': {'total_loan_amount': 1500, 'gross_incentive': 0,}, 'A09876543456': { 'total_loan_amount': 2000, 'gross_incentive': 0,}}

However, I'm getting output as follows my expectations is output of {'A002638841D': {'total_loan_amount': 2000, '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 is both the dict is getting updated as 2000 instead of 1500 and 2000 respectively total_loan_amount 是字典分别更新为 2000 而不是 1500 和 2000

When you assign the summary dict for each key, summary is a reference of the original summary variable, so you update twice the same dict.当您为每个键分配summary字典时,摘要是原始摘要变量的引用,因此您更新了相同的字典两次。 Maybe you could try也许你可以试试

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