【发布时间】:2019-05-10 18:33:37
【问题描述】:
我从一个文件中获得了几条不同的信息,这些信息已分类到列表中,并希望将它们添加到嵌套字典中。
输入
exon 65419 65433 gene_id "ENSG00000186092"; transcript_id "ENST00000641515"; exon_number 1
exon 65520 65573 gene_id "ENSG00000186092"; transcript_id "ENST00000641515"; exon_number 2
CDS 65565 65573 gene_id "ENSG00000186092"; transcript_id "ENST00000641515"; exon_number 2
exon 69037 71585 gene_id "ENSG00000186092"; transcript_id "ENST00000641515"; exon_number 3
CDS 69037 70005 gene_id "ENSG00000186092"; transcript_id "ENST00000641515"; exon_number 3
exon 69055 70108 gene_id "ENSG00000186092"; transcript_id "ENST00000335137"; exon_number 1
CDS 69091 70005 gene_id "ENSG00000186092"; transcript_id "ENST00000335137"; exon_number 1
期望的输出
{'ENSG00000186092': {'ENST00000335137': {'exon_start': ['69055'],
'exon_stop': ['70108']},
'ENST00000641515': {'exon_start': ['65419', '65520', '69037'],
'exon_stop': ['65433', '65573', '71585']}}}
当前尝试
class Vividict(dict):
def __missing__(self, key):
value = self[key] = type(self)() # retain local pointer to value
return value # faster to return than dict lookup
all_info = Vividict()
for line in infile:
if not line.startswith("##"):
item = line.rstrip().split("\t")
info = item[8].split(";")
geneID = info[0].split(" ")[1]
geneID = geneID.strip('\"')
gtf_t_id = info[1].split(" ")[2]
gtf_t_id = gtf_t_id.strip('\"')
if item[2] == "exon":
num = info[6].split(" ")[2]
start = item[3]
stop = item[4]
if start in all_info[geneID][gtf_t_id]["exon_start"]:
all_info[geneID][gtf_t_id]["exon_start"].append(start)
else:
all_info[geneID][gtf_t_id]["exon_start"] = [start]
if stop in all_info[geneID][gtf_t_id]["exon_stop"]:
all_info[geneID][gtf_t_id]["exon_stop"].append(stop)
else:
all_info[geneID][gtf_t_id]["exon_stop"] = [stop]
当前结果
{'ENSG00000186092': {'ENST00000335137': {'exon_start': ['69055'],
'exon_stop': ['70108']},
'ENST00000641515': {'exon_start': ['69037'],
'exon_stop': ['71585']}}}
【问题讨论】:
-
all_info[geneID][gtf_t_id]["exon_start"] += [start]和all_info[geneID][gtf_t_id]["exon_stop"] = [stop],为 {'exon_start':[],'exon_end':[]} 创建一个虚拟字典
标签: python dictionary nested