Mrplayr
Mrplayr

Reputation: 29

How to add an edge with the attributes of an already existing edge?

I am trying to create a reversed copy of edges if they have a a certain attribute as follows:

for i in list(G.edges(data=True, keys=True)):
    if i[3]['DIRECTIONA'] == 'bothDirections':
        G.add_edge(i[1],i[0],attr_dict=i[3])

The above works adequately with one inconvenience, the attributes are in a different format, instead of a simple dictionary of attributes this dictionary is now inside another dictionary under the key 'attr_dict'. Is there any way to simply have the dictionary of attribute without it being inside another one? It makes already written code not work since the format is different, thank you.

Upvotes: 0

Views: 475

Answers (1)

Sparky05
Sparky05

Reputation: 4892

You need to feed your edge attributes as multiple keywords arguments (usually represented in function signatures as **kwargs):

import networkx as nx

g = nx.DiGraph()
g.add_edge(1,2, DIRECTIONA="oneway")
g.add_edge(1,3, DIRECTIONA="oneway")
g.add_edge(1,4, DIRECTIONA="bothDirections")
g.add_edge(2,3, DIRECTIONA="bothDirections")
g.add_edge(2,4, DIRECTIONA="oneway")


print(g.edges(data=True))
# [(1, 2, {'DIRECTIONA': 'oneway'}), (1, 3, {'DIRECTIONA': 'oneway'}), (1, 4, {'DIRECTIONA': 'bothDirections'}), (2, 3, {'DIRECTIONA': 'bothDirections'}), (2, 4, {'DIRECTIONA': 'oneway'})]

custom_reversed = nx.DiGraph()
for node_from, node_to, edge_data in list(g.edges(data=True)):  # networkx 2.4 doesn not have key parameter
    if edge_data['DIRECTIONA'] == 'bothDirections':
        custom_reversed.add_edge(node_from, node_to, **edge_data)


print(custom_reversed.edges(data=True))
[(4, 1, {'DIRECTIONA': 'bothDirections'}), (3, 2, {'DIRECTIONA': 'bothDirections'})]

Upvotes: 1

Related Questions