Python Networkx 如何更新添加 'name' 作为属性的边?

Python Networkx how to update edge adding 'name' as an attribute?

我一直在使用 NetworkX 创建多向有向图,在实践中我偶然发现了一个我似乎无法正确回答的简单问题。

基本上我想 "separately" 随着时间的推移添加 "name" 属性,并在添加边缘属性时保留其关键字。我知道 "name" 可能是一个保留字,但是从我下面的代码来看,边缘数据仍然可以毫无问题地包含关键字 "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:

How can I update an existing single edge with a single attribute keyword 'name' and still appear in the edge attribute dict?

提前致谢!

你想要:

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'})]

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.