我正在编写一个程序,将数据存储在字典对象中,但此数据需要在程序执行期间的某个点保存,并在程序再次运行时加载回字典对象。 如何将字典对象转换为可以写入文件并加载回字典对象的字符串?这将有望支持包含字典的字典。
当前回答
我认为你应该考虑使用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}
其他回答
我认为你应该考虑使用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}
使用pickle模块将其保存到磁盘并稍后加载。
将字典转换为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)
我发现问题不在于我的dict对象,它是RubyString类型的键和值,加载后用rubymarshal 'loads'方法
所以我这样做了:
dic_items = dict.items()
new_dict = {str(key): str(value) for key, value in dic_items}
在中文中,你应该做以下调整:
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')
推荐文章
- 试图在Windows 10上运行Python时出现“权限被拒绝”
- 如何在Django中设置时区
- Swift:声明一个空字典
- 即使模板文件存在,Flask也会引发TemplateNotFound错误
- 将JSON字符串转换为HashMap
- 将JsonNode转换为POJO
- defaultdict的嵌套defaultdict
- 构造tkinter应用程序的最佳方法?
- 如何在Python中逐行打印字典?
- 当试图运行Python脚本时,“ImportError:没有命名模块”
- pylab和pyplot的区别是什么?
- Json_encode()转义正斜杠
- Argparse:确定使用了哪个子解析器
- django导入错误-没有core.management模块
- 在芹菜中检索队列中的任务列表