我一直在使用NetworkX来创建MultiDiGraph,在我的练习中,我偶然发现了一个简单的问题,我似乎无法做对。
基本上我想"分开"添加"名称"属性随着时间的推移,其关键字在边缘属性中添加时会被保留。我知道"名字"可能是一个保留字,但从下面的代码中看到,边数据仍然可以包含关键字" name"没有问题。
最后一个是我想要完成的事情。
#trying to update edge between 1,2 where there is still no 'name' attribute
G.edge[1][2]['name']='Lacuña'
#trying to add another edge to test if it will get the 'name' keyword
G.add_edge(9,10,name = 'Malolos')
print("\nNODES: " + str(G.nodes()))
print("EDGES: " + str(G.edges(data=True)))
输出:
NODES: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
EDGES: [(1, 2, {}), (1, 2, 'Lacu\xc3\xb1a'),
(4, 5, {'number': 282}), (4, 5, {'route': 37}),
(5, 4, {'number': '117'}), (6, 7, {}),
(7, 8, {}), (8, 9, {}), (9, 10, {'name': 'Malolos'})]
问题1:
G.edge[1][2]['name']='Lacuña'
问题2:
(9, 10, {'name': 'Malolos'})
的输出,其中关键字' name'出现在属性dict 如何使用单个属性更新现有单边 关键字' name'并且仍然出现在edge属性dict中?
提前谢谢!
答案 0 :(得分:3)
你想:
G[1][2]['name'] = 'Lacuña'
示例:
import networkx as nx
G = nx.Graph()
G.add_edge(1,2)
G[1][2]['name'] = 'Lacuña'
G.edges(data=True)
Out[1]: [(1, 2, {'name': 'Lacuña'})]
答案 1 :(得分:0)
I guess this will beneficial to beginners who might've overlooked between using DiGraph and MultiDiGraphs.
Problem 1 : Does not update edge data. Instead creates another edge with attribute value.
Given the code :
G.edge[1][2]['name']='Lacuña'
creates another edge instance and not in key-value pair,
while
G[1][2]['name']='Lacuña'
, will result to an error, in 'name'
Answer : MultiDiGraphs use G[u][v][key] format instead of the default G[u][v] for DiGraphs. Therefore when updating above, ['name'] was considered as a key which was not found; creating a new edge with that key and not as an attribute.
So to update a MultiDiGraph edge and add an attribute. The code should be like this:
G[1][2][0]['name'] = 'Lacuña' #where 0 is an incremental integer if not set
G.edges(data=True)
Out[1]: [(1, 2, 0, {'name': 'Lacuña'})]
While @harryscholes answer is how to update DiGraphs.