Reputation: 77
I have nodes with a list of attributes for each called 'times' in my case. I made a simple model like this and I get KeyError'times'. I need my graph save each node with a list of 'times' as an attribute. How can I fix it?
import networkx as nx
G = nx.DiGraph()
for u in range(10):
for t in range(5):
if G.has_node(u):
G[u]['times'].append(t)
else:
G.add_node(u,times=[t])
print(G.nodes(data=True))
Upvotes: 1
Views: 1153
Reputation: 77
This is what I was looking for, rather easy!
import networkx as nx
G = nx.DiGraph()
for u in range(2):
for t in range(5):
if u in G:
G.node[u]['times'].append(t)
else:
G.add_node(u,times=[t])
print(G.nodes(data=True))
Upvotes: 0
Reputation: 29953
You can do
G[u].setdefault('times', []).append(t)
instead of
G[u]['times'].append(t)
Upvotes: 1
Reputation: 40223
Try this
import networkx as nx
G = nx.DiGraph()
for u in range(10):
for t in range(5):
if G.has_node(u):
if not 'times' in G[u] # this
G[u]['times'] = [] # and this
G[u]['times'].append(t)
else:
G.add_node(u,times=[t])
print(G.nodes(data=True))
Upvotes: 0