1

I need to check if a node has an attribute (The attribute could not exist at all for a node). Something like this returs a "KeyError: 'size".

G = nx.Graph()
G.add_node("firstNode")
for node in G.nodes:
    if(G.nodes[node]['size'] is None):
        G.nodes[node]['size']=35    
#KeyError: 'size'
George Violettas
  • 334
  • 1
  • 14
  • please add additional information: what is not working? what is the desired result? Is there an error? – Michal Yanko Nov 03 '19 at 21:25
  • 1
    I updated my question according to your suggestion. The expected result is for the specific attribute ('size') to be added to a node if it doesnot exist. – George Violettas Nov 05 '19 at 15:23

1 Answers1

1

If we check what type of object is G.nodes[node] we can see this is a dictionary.

type(G.nodes[node])
# result <class 'dict'>

When you try to access an un-existing key in a dictionary you get this error. check out this question I'm getting Key error in python.

You have two ways to handle this:

import networkx as nx

G = nx.Graph()
G.add_node("firstNode")

# option 1

for node in G.nodes:
   node_dict = G.nodes[node]
   if node_dict.get('size') is None:
      node_dict['size']=35

# option 2

for node in G.nodes:
   node_dict = G.nodes[node]
   if 'size' not in node_dict or node_dict['size'] is None:
      node_dict['size']=35
Michal Yanko
  • 389
  • 1
  • 6