2015-04-06 44 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