从字典字符串生成词典

2024-10-01 07:36:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我从一个文件做了一个字典,需要把它写入另一个文件,我将对其进行编辑。为此,我从第一个文件制作了一个字典,并将其编成一个字符串以将其写入第二个文件。有没有办法把这个字符串转换回字典?在

第一个文件的示例是:

123 2
125 5
128 3

在第二个文件中,我把它做成了一个字典和一个字符串:

^{pr2}$

现在,我需要对这个新文件中的一些值进行编辑,但不确定如何将这个字典字符串返回到字典中。我只想把这个打印出来测试一下:

def EmpTrans(transactions_file, new_file):
    print(dict(new_file))

但这给了我一个空字典{}
我尽量不使用任何模块。我可以使用eval()。在


Tags: 模块文件字符串编辑示例new字典def
3条回答

将词典打印到文件:

output_file = open(path_to_stored_dictionary, 'w')
output_file.write(str(my_dictionary))
output_file.close()

从文件中读取词典:

^{pr2}$

注意@TigerhawkT3的评论:

...eval() executes code, which can be dangerous if untrusted sources will be sending strings to this function.

另一个安全函数是使用JSON。这里我使用json.dump()json.load()函数。唯一的障碍是json load将字符串作为unicode字符串返回,因此我使用自己的jsondeconder类,该类调用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

要将字符串转换回字典,需要将字符串拆分为键、值对的元组。要做到这一点,你要把它分开。在

def get_dict(s):
    return dict(map(lambda kv: kv.split(" "), s.split("\n")))

但我建议不要这样。在这种情况下,您应该使用Pickle模块,除非您不绝对信任数据。另请参见:How can I use pickle to save a dict?。在

^{pr2}$

dict_可以是任何对象。在

相关问题 更多 >