i'm using Python with MongoDB
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. 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
.
And then when you do - mylist.append(mydict)
- you are just appending None
(in the second case) .
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)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.