开发者

add nods and attribute list and KeyError!

I have nodes wit开发者_如何学运维h 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))


You can do

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

instead of

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


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))


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜