我有以下资料:
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语句的位置如何导致这样的更改?还是我在这里遗漏了什么
问题是您有相同的密钥,一个在数据中
amount
等于零,另一个在数据中amount
不是零在第一个循环中,首先创建具有非零
amount
的条目,然后被具有零amount
的条目覆盖因此,这两个代码都覆盖了一些条目,但是第一个代码覆盖了您想要保留的条目,而第二个代码(有效的代码)用零
amount
覆盖了条目问题是,在第一种情况下,您在这一行上覆盖了
names[report_id]
:让我们看一下
names
字典中的5a27cda63fff647c33a14b31
项:在循环的第一次迭代中,您正在设置
names[report_id]
的值:然后,由于金额为3000,字典更新为:
然后,在循环的第二次迭代中,字典被完全覆盖,导致
amount
值完全丢失:使用调试器逐行跟踪执行,观察
names
字典如何更改相关问题 更多 >
编程相关推荐