【问题标题】:Adding new values to a nested dictionary in python向python中的嵌套字典添加新值
【发布时间】: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


【解决方案1】:

您的代码工作正常,但是当开始/结束值新时它会继续初始化 并且不出现在该列表中,它会覆盖它并转到其他条件并制作 新列表包含 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]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-12-31
    • 1970-01-01
    • 2020-12-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-07
    相关资源
    最近更新 更多