nx.get_node_attributes 在 networkx 中返回空字典
nx.get_node_attributes in networkx returning an empty dictionary
代码如下:
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'))
虽然很奇怪,但我得到了一本空字典。有谁知道它的原因?或者还有其他可能的方法吗?
参考 link 关于类似的问题: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]
这是在documentation for adding attributes to nodes:
Node attributes
Add node attributes using add_node()
, add_nodes_from()
or 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'})]
这不是错误;你只是没有正确设置属性。
代码如下:
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'))
虽然很奇怪,但我得到了一本空字典。有谁知道它的原因?或者还有其他可能的方法吗? 参考 link 关于类似的问题: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]
这是在documentation for adding attributes to nodes:
Node attributes
Add node attributes using
add_node()
,add_nodes_from()
orG.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'})]
这不是错误;你只是没有正确设置属性。