在python的嵌套字典中添加新值

时间:2019-05-10 18:33:38

标签: python dictionary nested

我已经将文件分类到列表中,并希望将它们添加到嵌套词典中。

输入

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']}}}

1 个答案:

答案 0 :(得分:0)

您的代码可以正常工作,但是当开始/结束值变新时它会不断初始化 并没有出现在该列表中,它会覆盖它并转到其他条件并使 新列表包含1个元素

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]
            try:
                if all_info[geneID][gtf_t_id]["exon_start"]:
                        all_info[geneID][gtf_t_id]["exon_start"].append(start)

            except KeyError:
                all_info[geneID][gtf_t_id]["exon_start"] = [start]

            try:

                if  all_info[geneID][gtf_t_id]["exon_stop"]:
                    all_info[geneID][gtf_t_id]["exon_stop"].append(stop)
            except KeyError:
                all_info[geneID][gtf_t_id]["exon_stop"] = [stop]