DefaultDict在这两种情况下的行为都不同

2024-09-26 18:14:25 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下资料:

a = [{ "_id" : { "reportId" : "5a27cda63fff647c33a14b31" }, "amount" : 3000 },
     { "_id" : { "reportId" : "5a27cda63fff647c33a14b31", "name" : "sriram sathyan" }, "amount" : 0 },
     { "_id" : { "reportId" : "5a27cf173f978655f2efbee7" }, "amount" : 1200 },
     { "_id" : { "reportId" : "5a27cf173f978655f2efbee7", "name" : "karthik subbaraj" }, "amount" : 0 }
    ]

我想要以下结构:

{'reportid1':{'name':'sriram sathyan','amount':3000}, .....}

我尝试了以下代码:

names = defaultdict(dict)
for item in a:
   report_id = item['_id']['reportId']
   amount = item['amount']
   names[report_id] = {'name': item['_id'].get('name','')}
   if amount != 0:
      names[report_id].update({'amount': amount})
print(dict(names))

产出:

{'5a27cda63fff647c33a14b31': {'name': 'sriram sathyan'}, '5a27cf173f978655f2efbee7': {'name': 'karthik subbaraj'}}

(不是我想要的)

然后,我将上述代码更改为:

for item in a:
    report_id = item['_id']['reportId']
    amount = item['amount']
    if amount != 0:
        names[report_id] = {'amount': amount}
    names[report_id].update({'name': item['_id'].get('name','')})
print(dict(names))

这将产生:

{'5a27cda63fff647c33a14b31': {'amount': 3000, 'name': 'sriram sathyan'}, '5a27cf173f978655f2efbee7': {'amount': 1200, 'name': 'karthik subbaraj'}}

(我想要的!!!!!)

所以问题是=>; if语句的位置如何导致这样的更改?还是我在这里遗漏了什么


Tags: 代码namereportidforifnamesitem
2条回答

问题是您有相同的密钥,一个在数据中amount等于零,另一个在数据中amount不是

在第一个循环中,首先创建具有非零amount的条目,然后被具有零amount的条目覆盖

因此,这两个代码都覆盖了一些条目,但是第一个代码覆盖了您想要保留的条目,而第二个代码(有效的代码)用零amount覆盖了条目

问题是,在第一种情况下,您在这一行上覆盖了names[report_id]

names[report_id] = {'name': item['_id'].get('name','')}

让我们看一下names字典中的5a27cda63fff647c33a14b31项:

  1. 在循环的第一次迭代中,您正在设置names[report_id]的值:

    {'5a27cda63fff647c33a14b31': {'name': ''}}
    
  2. 然后,由于金额为3000,字典更新为:

    {'5a27cda63fff647c33a14b31': {'name': '', 'amount': 3000}}
    
  3. 然后,在循环的第二次迭代中,字典被完全覆盖,导致amount值完全丢失:

    {'5a27cda63fff647c33a14b31': {'name': 'sriram sathyan'}}
    

使用调试器逐行跟踪执行,观察names字典如何更改

相关问题 更多 >

    热门问题