我正在编写一个程序,将数据存储在字典对象中,但此数据需要在程序执行期间的某个点保存,并在程序再次运行时加载回字典对象。 如何将字典对象转换为可以写入文件并加载回字典对象的字符串?这将有望支持包含字典的字典。
当前回答
我使用yaml,如果需要可读(既不是JSON也不是XML, IMHO),或者如果阅读是不必要的,我使用pickle。
写
from pickle import dumps, loads
x = dict(a=1, b=2)
y = dict(c = x, z=3)
res = dumps(y)
open('/var/tmp/dump.txt', 'w').write(res)
读回
from pickle import dumps, loads
rev = loads(open('/var/tmp/dump.txt').read())
print rev
其他回答
我认为你应该考虑使用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}
json模块是一个很好的解决方案。与pickle相比,它的优点是只生成纯文本输出,并且是跨平台和跨版本的。
import json
json.dumps(dict)
我使用yaml,如果需要可读(既不是JSON也不是XML, IMHO),或者如果阅读是不必要的,我使用pickle。
写
from pickle import dumps, loads
x = dict(a=1, b=2)
y = dict(c = x, z=3)
res = dumps(y)
open('/var/tmp/dump.txt', 'w').write(res)
读回
from pickle import dumps, loads
rev = loads(open('/var/tmp/dump.txt').read())
print rev
您可能会发现json.dumps()方法需要帮助来处理某些对象类型。
这篇文章的答案如下:
import json
json.dumps(my_dictionary, indent=4, sort_keys=True, default=str)
将字典转换为JSON(字符串)
import json
mydict = { "name" : "Don",
"surname" : "Mandol",
"age" : 43}
result = json.dumps(mydict)
print(result[0:20])
会让你:
{"name": "Don", "sur .
将字符串转换为字典
back_to_mydict = json.loads(result)
推荐文章
- Visual Studio Code:如何调试Python脚本的参数
- 使用元组/列表等等。从输入vs直接引用类型如list/tuple/etc
- 结合conda环境。Yml和PIP requirements.txt
- 将命名元组转换为字典
- 如何使x轴和y轴的刻度相等呢?
- Numpy在这里函数多个条件
- 在Python中,使用argparse只允许正整数
- 如何排序mongodb与pymongo
- 不可变与可变类型
- 列表是线程安全的吗?
- 操作系统。makdirs在我的路径上不理解“~”
- 如何在Django模板中获得我的网站的域名?
- 在django Forms中定义css类
- 如何在Python中scp ?
- Numpy Max vs amax vs maximum