我正在编写一个程序,将数据存储在字典对象中,但此数据需要在程序执行期间的某个点保存,并在程序再次运行时加载回字典对象。 如何将字典对象转换为可以写入文件并加载回字典对象的字符串?这将有望支持包含字典的字典。
当前回答
我使用json:
import json
# convert to string
input_ = json.dumps({'id': id_ })
# load to dict
my_dict = json.loads(input_)
其他回答
json模块是一个很好的解决方案。与pickle相比,它的优点是只生成纯文本输出,并且是跨平台和跨版本的。
import json
json.dumps(dict)
我认为你应该考虑使用shelve模块,它提供了持久的文件支持的字典类对象。它很容易取代“真正的”字典,因为它几乎透明地为你的程序提供了可以像字典一样使用的东西,而不需要显式地将其转换为字符串,然后写入文件(反之亦然)。
主要的区别是需要在第一次使用之前首先打开()它,然后在完成时关闭()它(可能还需要同步()它,这取决于所使用的回写选项)。创建的任何“shelf”文件对象都可以包含常规字典作为值,允许它们在逻辑上嵌套。
这里有一个小例子:
import shelve
shelf = shelve.open('mydata') # open for reading and writing, creating if nec
shelf.update({'one':1, 'two':2, 'three': {'three.1': 3.1, 'three.2': 3.2 }})
shelf.close()
shelf = shelve.open('mydata')
print shelf
shelf.close()
输出:
{'three': {'three.1': 3.1, 'three.2': 3.2}, 'two': 2, 'one': 1}
我发现问题不在于我的dict对象,它是RubyString类型的键和值,加载后用rubymarshal 'loads'方法
所以我这样做了:
dic_items = dict.items()
new_dict = {str(key): str(value) for key, value in dic_items}
如果你关心速度,可以使用ujson (UltraJSON),它有和json相同的API:
import ujson
ujson.dumps([{"key": "value"}, 81, True])
# '[{"key":"value"},81,true]'
ujson.loads("""[{"key": "value"}, 81, true]""")
# [{u'key': u'value'}, 81, True]
我使用json:
import json
# convert to string
input_ = json.dumps({'id': id_ })
# load to dict
my_dict = json.loads(input_)