[英]How to read file into dictionary in python
I have a text file in the format of the following: 我有以下格式的文本文件:
hsa04012 [[['7039', '1956', '1398', '25'], ['7039', '1956', '1399', '25']], [['1839', '1956', '1398', '25'], ['1839', '1956', '1399', '25']], [['1399', '25']], [['1398', '25']], [['727738', '1956', '1398', '25'], ['727738', '1956', '1399', '25']], [['1956', '1398', '25'], ['1956', '1399', '25']], [['1950', '1956', '1398', '25'], ['1950', '1956', '1399', '25']], [['374', '1956', '1398', '25'], ['374', '1956', '1399', '25']], [['2069', '1956', '1398', '25'], ['2069', '1956', '1399', '25']], [['685', '1956', '1398', '25'], ['685', '1956', '1399', '25']]]
hsa02331...
How can I read the file into a dictionary with the key as the text containing hsa... and the value as the numbers within the brackets [as a list]. 如何将文件读入字典,其中的键为包含hsa ...的文本,值为方括号内的数字(作为列表)。
Thanks in advance 提前致谢
I'd use str.split
and ast.literal_eval
. 我会使用
str.split
和ast.literal_eval
。 That seems easiest... 这似乎最简单...
with open(datafile) as f:
d = {}
for line in f:
key,value = line.split(None,1)
d[key] = ast.literal_eval(value)
Although, you might be able to play some games with json
to get the lists as well. 虽然,您也许可以使用
json
玩一些游戏来获取列表。 The lists look to be quite valid JSON arrays, as they are called. 列表被称为是非常有效的JSON数组。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.