我从一个文件做了一个字典,需要把它写入另一个文件,我将对其进行编辑。为此,我从第一个文件制作了一个字典,并将其编成一个字符串以将其写入第二个文件。有没有办法把这个字符串转换回字典?在
第一个文件的示例是:
123 2
125 5
128 3
在第二个文件中,我把它做成了一个字典和一个字符串:
^{pr2}$现在,我需要对这个新文件中的一些值进行编辑,但不确定如何将这个字典字符串返回到字典中。我只想把这个打印出来测试一下:
def EmpTrans(transactions_file, new_file):
print(dict(new_file))
但这给了我一个空字典{}
。
我尽量不使用任何模块。我可以使用eval()。在
将词典打印到文件:
从文件中读取词典:
^{pr2}$注意@TigerhawkT3的评论:
另一个安全函数是使用JSON。这里我使用
json.dump()
和json.load()
函数。唯一的障碍是json load将字符串作为unicode字符串返回,因此我使用自己的jsondeconder类,该类调用super,然后遍历结果对字符串进行编码:要将字符串转换回字典,需要将字符串拆分为键、值对的元组。要做到这一点,你要把它分开。在
但我建议不要这样。在这种情况下,您应该使用Pickle模块,除非您不绝对信任数据。另请参见:How can I use pickle to save a dict?。在
^{pr2}$dict_
可以是任何对象。在相关问题 更多 >
编程相关推荐