导致KeyError创建嵌套字典

时间:2017-07-30 04:29:11

标签: python dictionary networkx

def pi_drug_target(graph, node):
    pi_to_drug_nodes = P.neighbors(node)
    nghr_targets = {}

    for pi_drug in pi_to_drug_nodes:
        nghr_targets[pi_drug] = {}
        nghr_targets[pi_drug]['treated with'] = []

        if B.has_node(pi_drug):
            drug_target = B.neighbors(pi_drug)

        for targets in drug_target:
            nghr_targets[pi_drug]['treated with'].append(targets)
            nghr_targets[targets]['treated with']['neighbors with'] = []

            if G.has_node(targets):
                gg_nodes = G.neighbors(targets)
                for ggn in gg_nodes:

                    if G.has_node(ggn):
                        nghr_targets[pi_drug]['treated with']['neighbors with'].append(ggn)
    return(nghr_targets)

KeyError                                  Traceback (most recent call last)
 <ipython-input-45-54c0755520e2> in <module>()
  ----> 1 pi_drug_target(P, 'DO218719')

 <ipython-input-42-22f6ce132dca> in pi_drug_target(graph, node)
 12             for targets in drug_target:
 13                 nghr_targets[pi_drug]['is treated with'].append(targets)
 ---> 14                 nghr_targets[targets]['treated with']['Gene neighbors with'] = []
 15 
 16                 if G.has_node(targets):

 KeyError: 'CYP19A1'

我有3个网络图P,B和G.我正在尝试创建一个函数,当我在P图中输入一个节点时,它会找到给定节点的相邻节点。然后,遍历这些邻居,并在另一个图(B)中找到它的邻居。然后,循环遍历那些找到的邻居 B图,并在另一个图(G)中再次找到邻居。我想创建一个嵌套字典,将节点显示为键,将邻居显示为值。这是我创建的代码,但即使我检查了节点确实存在于图中,我也得到了这个KeyError。

我刚开始编程并使用networkx。所以任何帮助表示赞赏!谢谢!

1 个答案:

答案 0 :(得分:1)

在主要for循环开始时,您有:nghr_targets[pi_drug] = {}

让我们第一次追踪那个循环。您为nghr_targets初始化的所有内容均为pi_drug。但是,您将nghr_targets与密钥targets一起使用。如果有任何targets不是pi_drug,那么第一次通过它必须失败。

在完成整个循环之前先将其初始化。或者甚至更好,使用defaultdict