2017-05-05 435 views
1

下面是代码:nx.get_node_attributes在networkx返回一个空的字典

import networkx as nx 
G=nx.Graph() 
G.add_nodes_from([0,1,2,3,4,5]) 
G[0]['color']="red" 
G[1]['color']="yellow" 
G[2]['color']="red" 
G[3]['color']="green" 
G[4]['color']="green" 
G[5]['color']="yellow" 
print(nx.get_node_attributes(G,'color')) 

奇怪,因为它是,我得到一个空的字典。有谁知道它的原因?或者还有其他可行的方法吗? 有关类似问题的参考链接:Networkx: how get attribute color from the graph

我知道以下是使用get_node_attributes方法的正确方法,但这是使用它的唯一方法吗?

>>> G=nx.Graph() 
>>> G.add_nodes_from([1,2,3],color='red') 
>>> color=nx.get_node_attributes(G,'color') 
>>> color[1] 
+1

[存储和访问节点属性python networkx]可能的重复(http://stackoverflow.com/questions/13698352/storing-and-accessing-node-attributes-python-networkx) – Joel

回答

2

这是documentation for adding attributes to nodes

节点属性

添加节点属性使用add_node()add_nodes_from()G.node

>>> G.add_node(1, time='5pm') 
>>> G.add_nodes_from([3], time='2pm') 
>>> G.node[1] 
{'time': '5pm'} 
>>> G.node[1]['room'] = 714 
>>> G.nodes(data=True) 
[(1, {'room': 714, 'time': '5pm'}), (3, {'time': '2pm'})] 

这不是一个bug;你只是没有正确设置属性。

+0

值得添加提及'nx。 set_node_attributes',它允许您在定义节点后设置属性。 – Joel