[英]Make dictionary from dictionary string
I made a dictionary from one file and need to write it into another file that I will be making edits to. 我从一个文件制作了一个词典,需要将其写入要编辑的另一个文件中。 To do this, I made a dictionary from the first file and made it into a string to write it to a second file.
为此,我从第一个文件制作了一个字典,并将其制成字符串以将其写入第二个文件。 Is there a way to convert this string back into a dictionary?
有没有办法将此字符串转换回字典?
An example of the first file is: 第一个文件的示例是:
123 2
125 5
128 3
which I make into a dictionary and make into a string in the second file: 我把它制成字典,然后在第二个文件中制成字符串:
def CreateNew(prefix, old_file):
new_file = open('new_file_name', 'w')
new_file.write(str(old_file))
new_file.close()
return new_file
Now, I need to make edits to some of the values in this new file, but am not sure how to make this dictionary string back into a dictionary. 现在,我需要对这个新文件中的某些值进行编辑,但是不确定如何将这个字典字符串重新变成字典。 I wanted to just print this off to test it out:
我只想将其打印出来进行测试:
def EmpTrans(transactions_file, new_file):
print(dict(new_file))
but this gives me an empty dictionary {}
. 但这给了我一个空的字典
{}
。
I'm trying not to use any modules for this. 我正在尝试不为此使用任何模块。 I was able to use eval().
我能够使用eval()。
To print a dictionary to a file: 要将字典打印到文件:
output_file = open(path_to_stored_dictionary, 'w')
output_file.write(str(my_dictionary))
output_file.close()
To read a dictionary from a file: 要从文件中读取字典:
my_dictionary = open(path_to_stored_dictionary, 'r').read()
my_dictionary = eval(my_dictionary)
Note @TigerhawkT3 's comment: 注意@ TigerhawkT3的评论:
...eval() executes code, which can be dangerous if untrusted sources will be sending strings to this function.
... eval()执行代码,如果不受信任的源将向此函数发送字符串,则可能很危险。
To turn your string back into a dictionary, you would split the string into a tuple of key, value pairs. 要将字符串转换成字典,您可以将字符串拆分为键,值对的元组。 To do so, you would split it.
为此,您将其拆分。
def get_dict(s):
return dict(map(lambda kv: kv.split(" "), s.split("\n")))
But I would advise against this. 但是我建议不要这样做。 In this case, you should use the Pickle module, except if you don't absolutely trust the data.
在这种情况下,您应该使用Pickle模块,除非您不是绝对信任数据。 See also: How can I use pickle to save a dict?
另请参阅: 如何使用泡菜保存字典? .
。
import pickle
def dump(dict_, file):
with open(file + ".pickle", "wb") as handle:
pickle.dump(dict_, handle)
def load(file):
with open(file + ".pickle", "rb") as handle:
return pickle.load(handle)
The dict_
can really be any object. dict_
实际上可以是任何对象。
Another secure function is using JSON. 另一个安全功能是使用JSON。 Here i use the
json.dump()
and json.load()
functions. 在这里,我使用
json.dump()
和json.load()
函数。 The only handicap, is that json load returns strings as unicode string, therefor i am using an own JSONDecoder class that calls super and then traverses the result to encode the strings: 唯一的障碍是json加载将字符串作为unicode字符串返回,因此我使用了自己的JSONDecoder类,该类调用super然后遍历结果以对字符串进行编码:
import json
from types import *
# your own decoder class to convert unicode to string type
class MyJSONDecoder(json.JSONDecoder):
# decode using our recursive function
def decode(self,json_string):
return self._decode_obj(super(MyJSONDecoder,self).decode(json_string))
# recursive function to traverse lists
def _decode_list(self,data):
decoded = []
for item in data:
if type(item) is UnicodeType: item = item.encode('utf-8')
elif type(item) is ListType: item = self._decode_list(item)
elif type(item) is DictType: item = self._decode_obj(item)
decoded.append(item)
return decoded
# recursive function to traverse objects
def _decode_obj(self,data):
decoded = {}
for key, value in data.iteritems():
if type(key) is UnicodeType: key = key.encode('utf-8')
if type(value) is UnicodeType: value = value.encode('utf-8')
elif type(value) is ListType: value = self._decode_list(value)
elif type(value) is DictType: value = self._decode_obj(value)
decoded[key] = value
return decoded
# the dictionary to save
dict = {
"123": 2,
"125": 4,
"126": 5,
"128": 6
}
# decoder instance
my_decoder = MyJSONDecoder()
# write object to file
with open('serialized.txt', 'w') as new_file:
json.dump(dict, new_file)
new_file.close()
print "Original", dict
# read object from file
with open ("serialized.txt", "r") as old_file:
dictcopy = my_decoder.decode(old_file.read())
old_file.close()
print "**Copy**", dictcopy
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.