我是一个ObjectId列表,我正在迭代到dict中的查找值,其中键是ObjectId。
email_count = 0
# user_id_list is a list of ObjectId's
for user_id in user_id_list:
# UuserIdemailCountD is a dict where they keys are objectIds
email_count += UuserIdemailCountD[user_id]
我一直收到以下错误:
email_count += UuserIdemailCountD[user_id]
KeyError: ObjectId('54a9c84ebf2e4e5b258b5412')
当我遍历user_id_list
并打印id时,我得到一个像54a9c84ebf2e4e5b258b5412
这样的普通字符串。
将字符串转换为ObjectId的答案是什么?如果是这样,怎么样?
答案 0 :(得分:15)
导入ObjectId:
from bson import ObjectId
从ObjectId到string:
oid = ObjectId()
oid_str = str(oid)
# oid_str is now '555fc7956cda204928c9dbab'
从string到ObjectId:
oid_str = '555fc7956cda204928c9dbab'
oid2 = ObjectId(oid_str)
print(repr(oid2))
# ObjectId('555fc7956cda204928c9dbab')