[英]python dict update trouble
i'm using Python with MongoDB我在 MongoDB 中使用 Python
why this code is working:为什么此代码有效:
for record in connection.collection.find():
mydict = dict(record)
mydict.update({"key": "value"})
mylist.append(mydict)
result:结果:
{"data": [{"anotherkey": "anothervalue"},{"key": "value"}]}
and this code is not working这个代码不工作
for record in connection.collection.find():
mydict = dict(record).update({"key": "value"})
mylist.append(mydict)
result:结果:
{"data": [null, null]}
Because dict.update()
is in-place, it does not return anything.因为
dict.update()
是就地的,它不会返回任何东西。 So when you do -所以当你这样做时——
mydict = dict(record).update({"key": "value"})
mydict
is actually None
, as if a function does not return anything in python, it by default returns None
. mydict
实际上是None
,就好像一个函数在 python 中不返回任何内容一样,它默认返回None
。
And then when you do - mylist.append(mydict)
- you are just appending None
(in the second case) .然后当你这样做 -
mylist.append(mydict)
- 你只是追加None
(在第二种情况下)。
update is an inplace operation mutating the original object:更新是一个改变原始对象的就地操作:
update([other])更新([其他])
Update the dictionary with the key/value pairs from other, overwriting existing keys.
使用其他键/值对更新字典,覆盖现有键。 Return None .
返回无。
You can use **
to get the behaviour you want:您可以使用
**
来获得您想要的行为:
mydict = dict(record,**{"key": "value"})
mylist.append(mydict)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.