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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4547274/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 16:16:01  来源:igfitidea点击:

Convert a python dict to a string and back

pythonjsondictionaryserialization

提问by AJ00200

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.

我正在编写一个将数据存储在字典对象中的程序,但是需要在程序执行期间的某个时刻保存这些数据,并在程序再次运行时将其加载回字典对象。如何将字典对象转换为可以写入文件并加载回字典对象的字符串?这将有望支持包含字典的字典。

采纳答案by Tyler Eaves

The json moduleis a good solution here. It has the advantages over pickle that it only produces plain text output, and is cross-platform and cross-version.

json 模块是一个很好的解决方案。与pickle相比,它的优点是只输出纯文本,并且是跨平台、跨版本的。

import json
json.dumps(dict)

回答by ismail

Use the picklemodule to save it to disk and load later on.

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

回答by PabloG

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_evalinstead of eval for additional security if the source is untrusted.

如果来源不受信任,您可以使用ast.literal_eval而不是 eval 来提高安全性。

回答by martineau

I think you should consider using the shelvemodule which provides persistent file-backed dictionary-like objects. 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).

我认为您应该考虑使用shelve提供持久文件支持的类似字典的对象的模块。它很容易代替“真正的”字典使用,因为它几乎透明地为您的程序提供了一些可以像字典一样使用的东西,而无需将其显式转换为字符串然后写入文件(反之亦然)反之)。

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 writebackoption being used). Any "shelf" file objects create can contain regular dictionaries as values, allowing them to be logically nested.

主要区别是需要open()在第一次使用之前先初始化它,然后close()在你完成后(可能是sync()ing 它,取决于writeback所使用的选项)。创建的任何“架子”文件对象都可以包含常规字典作为值,允许它们在逻辑上嵌套。

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}

回答by Gerard

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.

如果需要可读,我会使用 yaml(恕我直言,JSON 和 XML 都不是),或者如果不需要阅读,我会使用泡菜。

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

回答by Eyal Ch

I use json:

我使用json

import json

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

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

回答by beta

If in Chinses

如果在中国

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

回答by FightWithCode

Why not to use Python 3's inbuilt astlibrary's function literal_eval. It is better to use literal_evalinstead of eval

为什么不使用 Python 3 的内置ast库的函数literal_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 Stringthen, 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.

这是你喜欢的简单。

回答by Harvey

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

{"name": "Don", "sur

Convert string into dictionary

将字符串转换为字典

back_to_mydict = json.loads(result) 

回答by Tomasz Bartkowiak

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]