python dict更新问题
我在MongoDB中使用Python 此代码工作的原因:python dict更新问题,python,dictionary,Python,Dictionary,我在MongoDB中使用Python 此代码工作的原因: for record in connection.collection.find(): mydict = dict(record) mydict.update({"key": "value"}) mylist.append(mydict) 结果: {"data": [{"anotherkey": "anothervalue"},{"key": "value"}]} {"data": [null, null]}
for record in connection.collection.find():
mydict = dict(record)
mydict.update({"key": "value"})
mylist.append(mydict)
结果:
{"data": [{"anotherkey": "anothervalue"},{"key": "value"}]}
{"data": [null, null]}
该代码不工作
for record in connection.collection.find():
mydict = dict(record).update({"key": "value"})
mylist.append(mydict)
结果:
{"data": [{"anotherkey": "anothervalue"},{"key": "value"}]}
{"data": [null, null]}
因为dict.update()
已就位,所以它不会返回任何内容。所以当你这么做的时候-
mydict = dict(record).update({"key": "value"})
mydict
实际上是None
,就好像函数在python中不返回任何内容一样,默认情况下它会返回None
然后,当您执行-mylist.append(mydict)
-您只需追加None
(在第二种情况下)。更新是对原始对象的一种就地操作:
更新([其他])
使用其他键/值对更新字典,覆盖现有键返回无
您可以使用**
获得所需的行为:
mydict = dict(record,**{"key": "value"})
mylist.append(mydict)