如何在Python中将十六进制字符串转换为ObjectId [英] how to convert hex string to ObjectId in Python

查看:345
本文介绍了如何在Python中将十六进制字符串转换为ObjectId的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要遍历的Object列表,在其中键为ObjectId的字典中查找值.

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]

我一直收到以下错误:

email_count +=  UuserIdemailCountD[user_id]
KeyError: ObjectId('54a9c84ebf2e4e5b258b5412')

当我遍历user_id_list并仅打印id时,我得到一个像54a9c84ebf2e4e5b258b5412这样的纯字符串.

When i iterate over user_id_list and just print the ids, I get a plain string like this 54a9c84ebf2e4e5b258b5412.

将字符串转换为ObjectId的答案是吗?如果可以,怎么办?

Is the answer to convert the string to ObjectId's? If so, how?

推荐答案

导入ObjectId:

Import ObjectId:

from bson import ObjectId

从ObjectId到字符串:

From ObjectId to string:

oid = ObjectId()
oid_str = str(oid)
# oid_str is now '555fc7956cda204928c9dbab'

从字符串到ObjectId:

From string to ObjectId:

oid_str = '555fc7956cda204928c9dbab'
oid2 = ObjectId(oid_str)
print(repr(oid2))
# ObjectId('555fc7956cda204928c9dbab')

这篇关于如何在Python中将十六进制字符串转换为ObjectId的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆