出现问题:
rets = [{'id':1},{"id":2},{"id":3}]
context = {}
context['count'] = len(rets)
req = []
res = {}
for ret in rets:
res['a'] = ret['id']
req.append(res)
context['b'] = req
print(context)
如上述代码,想将rets中的数据通过for循环的方式添加到context里面想要得到如下类型的字典:
{'count': 3, 'b': [{'a': 1}, {'a': 2}, {'a': 3}]}
运行结果却是:
{'count': 3, 'b': [{'a': 3}, {'a': 3}, {'a': 3}]}
分析原因:
rets = [{'id':1},{"id":2},{"id":3}]
context = {}
context['count'] = len(rets)
req = []
res = {}
for ret in rets:
print(ret)
res['a'] = ret['id']
req.append(res)
print(req)
context['b'] = req
print(context)
打印每次结果:
{'id': 1}
[{'a': 1}]
{'id': 2}
[{'a': 2}, {'a': 2}]
{'id': 3}
[{'a': 3}, {'a': 3}, {'a': 3}]
{'count': 3, 'b': [{'a': 3}, {'a': 3}, {'a': 3}]}
发现每次for循环之后添加到字典中,都会覆盖掉上次添加的数据.
因为字典的增加方式dict1['aaa'] = bbb,这种形式是如果字典理由对应的key就会覆盖掉,没有对应的key就会添加到字典里。
解决办法:
rets = [{'id':1},{"id":2},{"id":3}]
context = {}
context['count'] = len(rets)
req = []
for ret in rets:
res = {}
print(ret)
res['a'] = ret['id']
req.append(res)
print(req)
context['b'] = req
print(context)
每次for循环都将字典初始化,然后再添加数据,就结觉问题了。
打印结果:
{'id': 1}
[{'a': 1}]
{'id': 2}
[{'a': 1}, {'a': 2}]
{'id': 3}
[{'a': 1}, {'a': 2}, {'a': 3}]
{'count': 3, 'b': [{'a': 1}, {'a': 2}, {'a': 3}]}
结束!