首页 > 解决方案 > 如何从python中的字典键中删除点

问题描述

我有python字典如下:

 data=df.to_dict('records')
 print(data)

给出输出:

    [{'id':'1','quantity.':2,'price':'350'},{'id':'2','quantity.':1,'price':'125'}, 
    {'id':'3','quantity.':4,'price':'500'}]

但是在使用命令插入 mongoDBcollection.insert_many(data)时,会出现如下错误:

bson.errors.InvalidDocument: key 'quantity.' must not contain '.'

由于我们无法在 MongoDB 中存储带有特殊字符的数据,所以我怎样才能删除这个点 '.' 来自所有键,这样我就可以在 MongoDB 中插入数据

标签: pythonmongodbdictionarypymongo

解决方案


这种理解应该可以做到。

data = [{k.replace('.', ''): v for k, v in d.items()} for d in data]

推荐阅读