>>> 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]}
這些數據會更容易處理,如果是JSON ... –
發佈的預期輸出 – RomanPerekhrest
這個文本文件是怎麼來呢?你爲什麼不使用一些既定的文本序列化格式?你在說什麼字典?沒有字典,除非你不談論文本文件。 –