2017-10-17 42 views
0

嗨,這是我目前的文本文件格式;如何在字典以某種方式格式化時從文本文件讀回數據? [Python]

A:{'1': [6, 4, 3, 8, 5], '2': [2, 1, 5, 4, 4], '3': []} 
B:{'1': [3, 6, 4, 3, 7], '2': [3, 2, 9, 2, 7], '3': []} 
C:{'1': [5, 4, 3, 6, 1], '2': [], '3': []} 

我該如何調用字典的關鍵字,並使其從文本文件中以格式化的方式打印數據。

+3

這些數據會更容易處理,如果是JSON ... –

+0

發佈的預期輸出 – RomanPerekhrest

+1

這個文本文件是怎麼來呢?你爲什麼不使用一些既定的文本序列化格式?你在說什麼字典?沒有字典,除非你不談論文本文件。 –

回答

1

您可以調用密鑰。例如: A['1'] 這將使你 [6, 4, 3, 8, 5]

0
>>> import ast 
# Read the file contents into a variable 
>>> file_content='''A:{'1': [6, 4, 3, 8, 5], '2': [2, 1, 5, 4, 4], '3': []} 
B:{'1': [3, 6, 4, 3, 7], '2': [3, 2, 9, 2, 7], '3': []} 
C:{'1': [5, 4, 3, 6, 1], '2': [], '3': []}''' 
>>> result_dict = {} 
>>> for line in file_content.split('\n'): 
     key_index = line.index(':') 
     result_dict[line[:key_index]] = ast.literal_eval(line[key_index+1:]) 


>>> result_dict 
{'A': {'1': [6, 4, 3, 8, 5], '3': [], '2': [2, 1, 5, 4, 4]}, 'C': {'1': [5, 4, 3, 6, 1], '3': [], '2': []}, 'B': {'1': [3, 6, 4, 3, 7], '3': [], '2': [3, 2, 9, 2, 7]}} 
>>> result_dict['A'] 
{'1': [6, 4, 3, 8, 5], '3': [], '2': [2, 1, 5, 4, 4]} 
相關問題