2015-04-06 46 views
0

我从一个文件制作了一本字典,并且需要将其写入另一个文件,我将对其进行编辑。为此,我从第一个文件创建了一个字典,并将其制作成字符串,以便将其写入第二个文件。有没有办法将这个字符串转换回字典?从词典字符串中制作字典

的第一个文件的一个例子是:

123 2 
125 5 
128 3 

我制作成一本字典,并进入第二个文件的字符串:

def CreateNew(prefix, old_file): 
    new_file = open('new_file_name', 'w') 
    new_file.write(str(old_file)) 
    new_file.close() 
    return new_file 

现在,我需要做编辑这个新文件中的一些值,但不知道如何将这个字典字符串转换回字典。我想只是打印这个功能来测试它:

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

但是这给了我一个空的字典{}
我正在尝试不为此使用任何模块。我能够使用eval()。

+0

的各种库和模块是一个Python最大的优势。然后你可以做'import ast',然后'my_dict = ast.literal_eval(my_dictionary_string)'和'my_dict'将是'dict'类型。 – TigerhawkT3

+1

[将字符串转换为字典?]的可能的重复(http://stackoverflow.com/questions/988228/converting-a-string-to-dictionary) – Celeo

+0

添加不使用任何模块的要求几乎保证答案是引入可能的安全问题或不填写所有要求。正如在推荐的重复问题的答案中所述,正确的方法是使用'ast'模块的'ast.literal_eval()'。 – TigerhawkT3

回答

1

要打印字典文件:

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

为了从文件中读取的字典:

my_dictionary = open(path_to_stored_dictionary, 'r').read() 
my_dictionary = eval(my_dictionary) 

@TigerhawkT3的评论:

... EVAL ()执行代码,如果不可信源将向此函数发送字符串,这可能很危险。

+0

如果字典不是真的字典呢?那里可能有任意代码。 –

+0

@PeterWood你是说我应该在顶部添加一行代码创建变量'my_dictionary'?或者这种方法是否有缺陷?我假设'my_dictionary'是一个字典,我的确概括了答案,但我确信OP可以很容易地将字典写入文件,并且'eval()'函数可以将一个字符串(这是字典)回到字典。 – jksnw

+1

他说'eval()'执行代码,如果不可信源将向此函数发送字符串,这会非常危险。 – TigerhawkT3

0

要将字符串变回字典,您需要将字符串拆分为键值对的元组。要做到这一点,你会分裂它。

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

但我会建议不要这样做。在这种情况下,除非您不完全信任数据,否则您应该使用Pickle模块。另见: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) 

dict_确实可以是任何物体。

0

另一个安全功能是使用JSON。这里我使用json.dump()json.load()函数。唯一的障碍是,JSON负载返回字符串为Unicode字符串,为此我使用调用超,然后遍历结果的自己JSONDecoder类编码字符串:

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