我正在尝试将包含DNA序列的文本文件转换为python中的字典。该文件是按列设置的。
TTT F
TCT S
TAT Y
TGT C
TTC F
import os.path
if os.path.isfile("GeneticCode_2.txt"):
f = open('GeneticCode_2.txt', 'r')
my_dict = eval(f.read())
试图让它:
my_dict = {TTT: F, TCT: S, TAT: Y}
答案 0 :(得分:2)
您可以使用dict
构造函数使用可迭代的对(2元组)并将其传递给文件的分割线:
with open('GeneticCode_2.txt', 'r') as f:
my_dict = dict(line.split() for line in f)
# works only if file only contains lines that split into exactly 2 tokens
答案 1 :(得分:0)
d = {}
with open("GeneticCode_2.txt") as infile:
for line in infile:
k,v = line.strip().split()
d[k] = v
答案 2 :(得分:0)
这不是最紧凑的方式,但它非常易读。
my_dict = dict()
for line in f.readlines():
parts = line.strip().split()
if not len(parts) < 2:
my_dict[parts[0]] = parts[1]