I a list of ObjectId's that I'm iterating over to the find values in a dict where the keys are ObjectId's.
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]
I keep getting the following error:
email_count +=  UuserIdemailCountD[user_id]
KeyError: ObjectId('54a9c84ebf2e4e5b258b5412')
When i iterate over user_id_list and just print the ids, I get a plain string like this 54a9c84ebf2e4e5b258b5412.
Is the answer to convert the string to ObjectId's? If so, how?
Import ObjectId:
from bson import ObjectId
From ObjectId to string:
oid = ObjectId()
oid_str = str(oid)
# oid_str is now '555fc7956cda204928c9dbab'
From string to ObjectId:
oid_str = '555fc7956cda204928c9dbab'
oid2 = ObjectId(oid_str)
print(repr(oid2))
# ObjectId('555fc7956cda204928c9dbab')
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With