Reputation: 345
I'm trying to write the following piece of code in python.
g = networkx.Digraph()
g.add_edge(1,2,x = 2)
The 'x' here is a variable. But networkx seems to take this as a name of the attribute. I need to pass what's inside x as the name of the attribute. How do I do it?
Upvotes: 3
Views: 1230
Reputation: 36715
add_edge
takes a dict
for attributes. You just need to put the attribute/value pairs in a dict
:
g.add_edge(1, 2, {x:2})
# or more explicitly
g.add_edge(1, 2, attr_dict={x:2})
Example:
In [25]: g = networkx.DiGraph()
In [26]: x = 'some string'
In [27]: g.add_edge(1, 2, {x:2})
In [28]: g[1][2]
Out[28]: {'some string': 2}
Upvotes: 2
Reputation: 78610
g = networkx.Digraph()
g.add_edge(1, 2, **{x: 2})
See how to use *args and **kwargs in Python. Alternatively, networkx
also allows you to give it directly as a dictionary:
g.add_edge(1, 2, {x: 2})
Upvotes: 2