0
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'

I have 3 networkx graphs P, B, and G. I am trying to create a function where, when I input a node in P graph, it would find the given node's neighboring nodes. Then, iterate through those neighbors, and find it's neighbors in another graph (B). Then, loop through those neighbors found in B graph, and find the neighbors again in another graph (G). I want to create a nested dictionary that shows nodes as keys and neighbors as values. This is the code I created, but I am getting this KeyError even though I checked that the node does exist in the graph.

I just started programming and using networkx. So any help is appreciated! Thank you!

hsy_99
  • 55
  • 6

1 Answers1

1

At the start of your main for loop you have: nghr_targets[pi_drug] = {}.

Let's trace that loop the first time through. All you've initialized for nghr_targets is for pi_drug. But then you use nghr_targets with the key targets. If there are any targets that are not pi_drug, then the first time through it must fail.

Initialize it first before going through the entire loop. Or even better, use a defaultdict.

Joel
  • 22,598
  • 6
  • 69
  • 93
  • Thank you! Haven't worked with defaultdict yet so I tweaked it according to your suggestion about initializing first before looping and it worked! – hsy_99 Jul 30 '17 at 05:21