首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >在dict中更新特定dict的键

在dict中更新特定dict的键
EN

Stack Overflow用户
提问于 2022-02-22 09:42:22
回答 1查看 24关注 0票数 0

我正在创建字典字典,然后尝试使用for循环更新特定的键。但是,所有的键都在更新。

守则如下:

代码语言:javascript
运行
复制
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。

EN

Stack Overflow用户

发布于 2022-02-22 09:51:20

当为每个键分配summary dict时,摘要是原始摘要变量的引用,因此更新两次相同的dict。也许你可以试试

代码语言:javascript
运行
复制
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)
票数 1
EN
查看全部 1 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/71218974

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档