masti
masti

Reputation: 77

add nods and attribute list and KeyError!

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

Answers (3)

masti
masti

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

Johannes Charra
Johannes Charra

Reputation: 29953

You can do

G[u].setdefault('times', []).append(t)

instead of

G[u]['times'].append(t)

Upvotes: 1

Matt Williamson
Matt Williamson

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

Related Questions