我正在编写一个将数据存储在字典对象中的程序,但是这些数据需要在程序执行期间的某个时刻保存,并在程序再次运行时加载回字典对象中。 如何将字典对象转换为可以写入文件并加载回字典对象的字符串?这有望支持包含字典的字典。
json 模块 是一个很好的解决方案。它比pickle的优点是它只产生纯文本输出,并且是跨平台和跨版本的。
import json
json.dumps(dict)
如果你的字典不是太大,也许 str + eval 可以完成这项工作:
dict1 = {'one':1, 'two':2, 'three': {'three.1': 3.1, 'three.2': 3.2 }}
str1 = str(dict1)
dict2 = eval(str1)
print(dict1 == dict2)
如果来源不受信任,您可以使用 ast.literal_eval 代替 eval 以提高安全性。
json
:
import json
# convert to string
input_ = json.dumps({'id': id_ })
# load to dict
my_dict = json.loads(input_)
为什么不使用Python 3内置的ast库的函数literal_eval。最好使用 literal_eval 而不是 eval
import ast
str_of_dict = "{'key1': 'key1value', 'key2': 'key2value'}"
ast.literal_eval(str_of_dict)
将给出实际字典的输出
{'key1': 'key1value', 'key2': 'key2value'}
如果您要求将 Dictionary 转换为 String 那么,使用 Python 的 str() 方法怎么样。
假设字典是:
my_dict = {'key1': 'key1value', 'key2': 'key2value'}
这将像这样完成:
str(my_dict)
将打印:
"{'key1': 'key1value', 'key2': 'key2value'}"
这就是你喜欢的简单方法。
pickle
模块将其保存到磁盘并稍后加载。
将字典转换为JSON(字符串)
import json
mydict = { "name" : "Don",
"surname" : "Mandol",
"age" : 43}
result = json.dumps(mydict)
print(result[0:20])
会给你:
{“姓名”:“唐”,“苏尔
将字符串转换为字典
back_to_mydict = json.loads(result)
在中文中你应该做以下调整:
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')
您可能会发现
json.dumps()
方法需要帮助来处理某些对象类型。
以下内容归功于这篇文章的最佳答案:
import json
json.dumps(my_dictionary, indent=4, sort_keys=True, default=str)
shelve
模块,它提供持久文件支持的类似字典的对象。它很容易代替“真正的”字典,因为它几乎透明地为您的程序提供了可以像字典一样使用的东西,而不需要显式地将其转换为字符串,然后写入文件(或者反之亦然)反之亦然)。
主要区别是在首次使用之前需要先
open()
,然后在完成后close()
(可能还需要sync()
,具体取决于所使用的writeback
选项)。创建的任何“架子”文件对象都可以包含常规字典作为值,从而允许它们逻辑嵌套。
这是一个简单的例子:
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}
如果你关心速度,请使用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 都不是),或者如果不需要读取,我使用 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
我发现问题不在于我的 dict 对象,而是使用 RubyMarshl“loads”方法加载后 RubyString 类型的键和值
所以我这样做了:
dic_items = dict.items()
new_dict = {str(key): str(value) for key, value in dic_items}