我正在编写一个程序,将数据存储在字典对象中,但此数据需要在程序执行期间的某个点保存,并在程序再次运行时加载回字典对象。 如何将字典对象转换为可以写入文件并加载回字典对象的字符串?这将有望支持包含字典的字典。
当前回答
在中文中,你应该做以下调整:
import codecs
fout = codecs.open("xxx.json", "w", "utf-8")
dict_to_json = json.dumps({'text':"中文"},ensure_ascii=False,indent=2)
fout.write(dict_to_json + '\n')
其他回答
如果你关心速度,可以使用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]
我使用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模块是一个很好的解决方案。与pickle相比,它的优点是只生成纯文本输出,并且是跨平台和跨版本的。
import json
json.dumps(dict)
我使用json:
import json
# convert to string
input_ = json.dumps({'id': id_ })
# load to dict
my_dict = json.loads(input_)
在中文中,你应该做以下调整:
import codecs
fout = codecs.open("xxx.json", "w", "utf-8")
dict_to_json = json.dumps({'text':"中文"},ensure_ascii=False,indent=2)
fout.write(dict_to_json + '\n')
推荐文章
- 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