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

问题:将python字典转换为字符串并返回

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

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.


回答 0

json模块是一个很好的解决方案。与pickle相比,它的优势在于它仅生成纯文本输出,并且是跨平台和跨版本的。

import json
json.dumps(dict)

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

import json
json.dumps(dict)

回答 1

如果您的字典不太大,也许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来提高安全性。

If your dictionary isn’t too big maybe str + eval can do the work:

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.


回答 2

我用json

import json

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

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

I use json:

import json

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

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

回答 3

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

Use the pickle module to save it to disk and load later on.


回答 4

为什么不使用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,那么如何使用str() Python的方法。

假设字典是:

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

这将像这样完成:

str(my_dict)

将打印:

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

这是您想要的简单操作。

Why not to use Python 3’s inbuilt ast library’s function literal_eval. It is better to use literal_eval instead of 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.

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.


回答 5

如果在中国

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

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

回答 6

将字典转换成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) 

Convert dictionary into JSON (string)

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) 

回答 7

我认为您应该考虑使用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}

I think you should consider using the shelve module 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).

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). 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}

回答 8

如果您关心速度,请使用与json相同的API的ujson(UltraJSON):

import ujson
ujson.dumps([{"key": "value"}, 81, True])
# '[{"key":"value"},81,true]'
ujson.loads("""[{"key": "value"}, 81, true]""")
# [{u'key': u'value'}, 81, True]

If you care about the speed use ujson (UltraJSON), which has the same API as json:

import ujson
ujson.dumps([{"key": "value"}, 81, True])
# '[{"key":"value"},81,true]'
ujson.loads("""[{"key": "value"}, 81, true]""")
# [{u'key': u'value'}, 81, True]

回答 9

如果需要可读性(不是IMHO的JSON或XML),或者如果不需要阅读的话,我就使用yaml。

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

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.

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