Python 在数据库中缓存大型非unicode字典?

Python 在数据库中缓存大型非unicode字典?,python,mongodb,dictionary,data-dictionary,database,Python,Mongodb,Dictionary,Data Dictionary,Database,我有一个大字典(输出为366MB的字符串,~383764153行filetextfile),我想将其存储在数据库中,以便快速访问,并跳过填充字典所需的计算时间 我的字典由文件名/内容对字典组成。小子集: { 'Reuters/19960916': { '54826newsML': '<?xml version="1.0" encoding="iso-8859-1" ?>\r\n<newsitem itemid="54826" id="root" date

我有一个大字典(输出为366MB的字符串,~383764153行filetextfile),我想将其存储在数据库中,以便快速访问,并跳过填充字典所需的计算时间

我的字典由文件名/内容对字典组成。小子集:

{
    'Reuters/19960916': {
        '54826newsML': '<?xml version="1.0"
encoding="iso-8859-1" ?>\r\n<newsitem itemid="54826" id="root"
date="1996-09-16" xml:lang="en">\r\n<title>USA: RESEARCH ALERT -
Crestar Financial cut.</title>\r\n<headline>RESEARCH ALERT - Crestar
Financial cut.</headline>\r\n<text>\n<p>-- Salomon Brothers analyst
Carole Berger said she cut her rating on Crestar Financial Corp to
hold from buy, at the same time lowering her 1997 earnings per share
view to $5.40 from $5.85.</p>\n<p>-- Crestar said it would buy
Citizens Bancorp in a $774 million stock swap.</p>\n<p>-- Crestar
shares were down 2-1/2 at 58-7/8. Citizens Bancorp soared 14-5/8 to
46-7/8.</p>\n</text>\r\n<copyright>(c) Reuters Limited',
        '55964newsML': '<?xml version="1.0" encoding="iso-8859-1"
?>\r\n<newsitem itemid="55964" id="root" date="1996-09-16"
xml:lang="en">\r\n<title>USA: Nebraska cattle sales thin at
$114/dressed-feedlot.</title>\r\n'
    }
}
{
“路透社/19960916”:{
“54826newsML”:“\r\n\r\nUSA:研究警报-
Crestar财务中断。\r\n研究警报-Crestar
财务削减。\r\n\n--所罗门兄弟分析师
Carole Berger说她将Crestar Financial Corp的评级下调至
从买入中持有,同时降低了她1997年的每股收益
从5.85美元降至5.40美元。

\n--Crestar表示将购买 公民银行进行了7.74亿美元的股票互换。

\n--快思达 股价下跌2-1/2,报58-7/8。公民银行股价飙升14-5/8,报58-7/8 46-7/8.

\n\r\n(c)路透社有限公司, '55964newsML':'\r\n\r\nUSA:内布拉斯加州的牛销售量在 114美元/精加工饲养场。\r\n' } }
我认为这很合适,但它似乎要求键和值都必须是Unicode,而且因为我从
ZipFile
上的
namelist()
中获取文件名,所以不能保证是Unicode

您建议我如何将此词典序列化到数据库中?

如果您有RAM(显然是这样,因为您首先填充了词典)--
cPickle
。或者,如果您想要一些需要更少RAM但速度较慢的东西--shelve

pymongo不要求字符串为unicode,它实际上会按原样发送ascii Sting,并将unicode编码为UTF8。从pymongo检索数据时,您始终可以使用unicode。@@@

如果您的输入包含具有高阶字节的“国际”字节字符串(如
ab\xC3cd
),则需要将这些字符串转换为unicode或将其编码为UTF-8。下面是一个处理任意嵌套dict的简单递归转换器:

def unicode_all(s):
    if isinstance(s, dict):
        return dict((unicode(k), unicode_all(v)) for k, v in s.items())
    if isinstance(s, list):
        return [unicode_all(v) for v in s]
    return unicode(s)

我在过去研究过shelve,在最坏的情况下,cPickle对于在数据库中存储非unicode可能是有用的,但我认为我正在寻找一个纯数据库解决方案。无论如何,谢谢,那么我为什么会遇到这个错误?:
回溯(最近一次调用最后一次):文件“outlay.py”,第33行,在subset.insert(myinput)文件“c:\src\pymongo\pymongo\collection.py”,第306行,在insert continue\u on\u error,self.\u uuid\u subtype中),safe)bson.errors.InvalidStringData:文档中的字符串必须是有效的UTF-8
@user143803:这是因为您的输入包含非拉丁字节字符串。请参阅更新。谢谢,但我以前的解决方案也使用了
unicode()
,但仍然给了我这个错误。我现在已经解决了,虽然使用了汤中的Unicodammit