简体   繁体   中英

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

I've been using NetworkX to create a MultiDiGraph and upon my practice I stumbled upon probably a simple question that I can't seem to get right.

Basically I wanted to "separately" add the "name" attribute over time with its keyword being preserved as it adds in the edge attributes. I know that "name" could be a reserved word, but seeing that from the code I have below, edge data can still contain the keyword "name" with no problems.

The last one is what I am trying to accomplish.

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

Output:

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

Problem 1:

G.edge[1][2]['name']='Lacuña'
  • Does not update edge data. Instead creates another edge with attribute value

Problem 2:

  • Does not create the output similar to (9, 10, {'name': 'Malolos'}) , where keyword 'name' appears in attribute dict

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

Thank you in advance!

You want:

G[1][2]['name'] = 'Lacuña'

Example:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM