我正在创建字典字典,然后尝试使用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)total_loan_amount for A002638841D是1500
total_loan_amount for A09876543456是2000年
我的期望是print(seller_summary)的输出应该是{'A002638841D': {'total_loan_amount': 1500, 'gross_incentive': 0,}, 'A09876543456': { 'total_loan_amount': 2000, 'gross_incentive': 0,}}
但是,我得到的输出如下:我的期望是{'A002638841D': {'total_loan_amount': 2000, 'gross_incentive': 0,}, 'A09876543456': { 'total_loan_amount': 2000, 'gross_incentive': 0,}}的输出
total_loan_amount是dict被更新为2000年而不是分别为1500和2000。
发布于 2022-02-22 09:51:20
当为每个键分配summary dict时,摘要是原始摘要变量的引用,因此更新两次相同的dict。也许你可以试试
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)https://stackoverflow.com/questions/71218974
复制相似问题