Python 3.x 将带有数字键的数据插入mongodb(python字典中的GPS数据)时出错
我正在尝试使用Python 3.x 将带有数字键的数据插入mongodb(python字典中的GPS数据)时出错,python-3.x,mongodb,dictionary,pymongo,Python 3.x,Mongodb,Dictionary,Pymongo,我正在尝试使用pymongo将一些图像元数据存储到MongoDB中。但是我在插入时出错了 #Data in Dictionary gps = {'GPSInfo': {1: 'N', 2: ((38, 1), (54, 1), (3540, 100)), 3: 'E', 4: ((1, 1), (26, 1), (1920, 100)), 5: b'\x00', 6: (0, 1), 7: ((11, 1), (7, 1), (47, 1)), 16: 'T', 17: (5338, 65),
pymongo
将一些图像元数据存储到MongoDB
中。但是我在插入时出错了
#Data in Dictionary
gps = {'GPSInfo': {1: 'N', 2: ((38, 1), (54, 1), (3540, 100)), 3: 'E', 4: ((1, 1), (26, 1), (1920, 100)), 5: b'\x00', 6: (0, 1), 7: ((11, 1), (7, 1), (47, 1)), 16: 'T', 17: (5338, 65), 29: '2011:09:04'}}
import pymongo
mng_client = pymongo.MongoClient('localhost', 27017)
mng_db = mng_client['pic_db']
collection_name = 'pic_audit_log2'
db_cm = mng_db[collection_name]
# Insert data from a dictionary
db_cm.remove()
db_cm.insert(gps)
错误
我是否必须将所有数字字典键更改为字符串?
当我这样做的时候,它就起作用了
d = {str(a):{str(c):d for c,d in b.items()} if isinstance(b,dict) else b for a,b in gps.items()}
# Insert data from dictionary
db_cm.remove()
db_cm.insert(d)
还有其他更好的选择吗?在插入数据时,mongo shell会将整数转换为字符串,但pymongo不会。您的解决方案可能与其他解决方案一样好
d = {str(a):{str(c):d for c,d in b.items()} if isinstance(b,dict) else b for a,b in gps.items()}
# Insert data from dictionary
db_cm.remove()
db_cm.insert(d)