如何在Python中将十六进制字符串转换为ObjectId
我需要一个ObjectId列表,我正在迭代该列表,以查找dict中的值,其中键是ObjectId如何在Python中将十六进制字符串转换为ObjectId,python,mongodb,python-2.7,pymongo,Python,Mongodb,Python 2.7,Pymongo,我需要一个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 = 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\u id\u list
并只打印id时,我得到一个像这样的普通字符串54a9c84ebf2e4e5b258b5412
是将字符串转换为ObjectId的答案吗?如果是,如何导入?导入对象ID:
from bson import ObjectId
oid_str = '555fc7956cda204928c9dbab'
oid2 = ObjectId(oid_str)
print(repr(oid2))
# ObjectId('555fc7956cda204928c9dbab')
从ObjectId到字符串:
oid = ObjectId()
oid_str = str(oid)
# oid_str is now '555fc7956cda204928c9dbab'
从字符串到对象ID:
from bson import ObjectId
oid_str = '555fc7956cda204928c9dbab'
oid2 = ObjectId(oid_str)
print(repr(oid2))
# ObjectId('555fc7956cda204928c9dbab')
尝试以下操作:email\u count+=UuserIdemailCountD.get(user\u id,0),因此如果user\u id不存在,它将返回0,这不会影响结果……UuserIdemailCountD dict中的值都是数值,对吗?这很有效。为什么要买?你得到的是正确的
email\u count
还是零?