简体   繁体   English

将python dict转换为字符串并返回

[英]Convert a python dict to a string and back

I am writing a program that stores data in a dictionary object, but this data needs to be saved at some point during the program execution and loaded back into the dictionary object when the program is run again.我正在编写一个将数据存储在字典对象中的程序,但是这些数据需要在程序执行期间的某个时间点保存,并在程序再次运行时加载回字典对象。 How would I convert a dictionary object into a string that can be written to a file and loaded back into a dictionary object?如何将字典对象转换为可以写入文件并加载回字典对象的字符串? This will hopefully support dictionaries containing dictionaries.这将有望支持包含字典的字典。

The json module is a good solution here. json 模块在这里是一个很好的解决方案。 It has the advantages over pickle that it only produces plain text output, and is cross-platform and cross-version.与pickle相比,它的优点是只产生纯文本输出,并且是跨平台和跨版本的。

import json
json.dumps(dict)

If your dictionary isn't too big maybe str + eval can do the work:如果您的字典不是太大,也许 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)

You can use ast.literal_eval instead of eval for additional security if the source is untrusted.如果源不受信任,您可以使用ast.literal_eval代替 eval 以获得额外的安全性。

I use json :我使用json

import json

# convert to string
input = json.dumps({'id': id })

# load to dict
my_dict = json.loads(input) 

Why not to use Python 3's inbuilt ast library's function literal_eval .为什么不使用 Python 3 的内置ast库的函数literal_eval It is better to use literal_eval instead of eval最好使用literal_eval而不是eval

import ast
str_of_dict = "{'key1': 'key1value', 'key2': 'key2value'}"
ast.literal_eval(str_of_dict)

will give output as actual Dictionary将输出作为实际字典

{'key1': 'key1value', 'key2': 'key2value'}

And If you are asking to convert a Dictionary to a String then, How about using str() method of Python.如果您要求将字典转换为字符串,那么使用 Python 的str()方法怎么样。

Suppose the dictionary is :假设字典是:

my_dict = {'key1': 'key1value', 'key2': 'key2value'}

And this will be done like this :这将像这样完成:

str(my_dict)

Will Print :将打印:

"{'key1': 'key1value', 'key2': 'key2value'}"

This is the easy as you like.这是你喜欢的简单。

使用pickle模块将其保存到磁盘并稍后加载。

Convert dictionary into JSON (string)将字典转换为 JSON(字符串)

import json 

mydict = { "name" : "Don", 
          "surname" : "Mandol", 
          "age" : 43} 

result = json.dumps(mydict)

print(result[0:20])

will get you:会给你:

{"name": "Don", "sur {“名称”:“唐”,“苏尔

Convert string into dictionary将字符串转换为字典

back_to_mydict = json.loads(result) 

In Chinese language you should do the following adjustments:在中文中,您应该进行以下调整:

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')

I think you should consider using the shelve module which provides persistent file-backed dictionary-like objects.我认为您应该考虑使用提供持久文件支持的类字典对象的shelve模块。 It's easy to use in place of a "real" dictionary because it almost transparently provides your program with something that can be used just like a dictionary, without the need to explicitly convert it to a string and then write to a file (or vice-versa).它很容易代替“真正的”字典,因为它几乎透明地为您的程序提供了可以像字典一样使用的东西,而无需将其显式转换为字符串然后写入文件(或副 -反之亦然)。

The main difference is needing to initially open() it before first use and then close() it when you're done (and possibly sync() ing it, depending on the writeback option being used).主要区别是需要在首次使用之前首先open()它,然后在完成后close()它(并且可能sync()它,取决于正在使用的writeback选项)。 Any "shelf" file objects create can contain regular dictionaries as values, allowing them to be logically nested.创建的任何“架子”文件对象都可以包含常规字典作为值,从而允许它们在逻辑上嵌套。

Here's a trivial example:这是一个简单的例子:

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()

Output:输出:

{'three': {'three.1': 3.1, 'three.2': 3.2}, 'two': 2, 'one': 1}

You may find the json.dumps() method needs help handling some object types.您可能会发现json.dumps()方法需要帮助处理某些对象类型。

Credit goes to the top answer of this post for the following:归功于以下内容的这篇文章的最佳答案:

import json
json.dumps(my_dictionary, indent=4, sort_keys=True, default=str)

If you care about the speed use ujson (UltraJSON), which has the same API as json:如果您关心速度,请使用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]

I use yaml for that if needs to be readable (neither JSON nor XML are that IMHO), or if reading is not necessary I use pickle.如果需要可读(恕我直言,JSON 和 XML 都不是),或者如果不需要读取,我使用 yaml。

Write

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)

Read back回过头再读

from pickle import dumps, loads
rev = loads(open('/var/tmp/dump.txt').read())
print rev

I figured out the problem was not with my dict object it was the keys and values that were of RubyString type after loading it with RubyMarshl 'loads' method我发现问题不在于我的 dict 对象,而是使用 RubyMarshl 'loads' 方法加载它后属于 RubyString 类型的键和值

So i did this:所以我这样做了:

dic_items = dict.items()
new_dict = {str(key): str(value) for key, value in dic_items}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM