views:

37

answers:

5

Hi! 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))
A: 

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))
Matt Williamson
what I got from this is each node with only one number in 'times':[(0, {'times': [0]})] ...but I'm looking for this:[(0,{'times':[0,1,2,3]})] ...sorry my sample is a bit stupid!
masti
+1  A: 

You can do

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

instead of

G[u]['times'].append(t)
jellybean
still it gets me the same result: [(0, {'times': [0]})] etc ...but I'm looking for this: [(0,{'times':[0,1,2,3]})] :(
masti
A: 

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)) 
masti
A: 

Is it possible to print attribute values in graph display using say draw_networkx or something ?

SDR