NetworkX: how to add weights to an existing G.edges()?
<p>Given any graph G created in NetworkX, I want to be able to assign some weights to  G.edges() <strong>after</strong> the graph is created. The graphs involved are grids, erdos-reyni, barabasi-albert, and so forth. </p>

<p>Given my <code>G.edges()</code>:</p>

<pre><code>[(0, 1), (0, 10), (1, 11), (1, 2), (2, 3), (2, 12), ...]
</code></pre>

<p>And my <code>weights</code>:</p>

<pre><code>{(0,1):1.0, (0,10):1.0, (1,2):1.0, (1,11):1.0, (2,3):1.0, (2,12):1.0, ...}
</code></pre>

<p><strong>How can I assign each edge the relevant weight?</strong> In this trivial case all weights are 1.</p>

<p>I've tried to add the weights to G.edges() directly like this</p>

<pre><code>for i, edge in enumerate(G.edges()):
    G.edges[i]['weight']=weights[edge]
</code></pre>

<p>But I get this error:</p>

<pre><code>---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
&lt;ipython-input-48-6119dc6b7af0&gt; in &lt;module&gt;()
     10 
     11 for i, edge in enumerate(G.edges()):
---&gt; 12     G.edges[i]['weight']=weights[edge]

TypeError: 'instancemethod' object has no attribute '__getitem__'
</code></pre>

<p><strong>What's wrong?</strong> Since <code>G.edges()</code> is a list, why can't I access its elements as with any other list?</p>

<p>It fails because <code>edges</code> is a method.</p>

<p>The <a href="https://networkx.github.io/documentation/development/reference/generated/networkx.Graph.get_edge_data.html" rel="nofollow">documentation</a> says to do this like:</p>

<pre><code>G[source][target]['weight'] = weight
</code></pre>

<p>For example, the following works for me:</p>

<pre><code>import networkx as nx

G = nx.Graph()

G.add_path([0, 1, 2, 3])

G[0][1]['weight'] = 3

&gt;&gt;&gt; G.get_edge_data(0, 1)
{'weight': 3}
</code></pre>

<p>However, your type of code indeed fails:</p>

<pre><code>G.edges[0][1]['weight'] = 3
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
&lt;ipython-input-14-97b10ad2279a&gt; in &lt;module&gt;()
----&gt; 1 G.edges[0][1]['weight'] = 3

TypeError: 'instancemethod' object has no attribute '__getitem__'
</code></pre>

<hr>

<p>In your case, I'd suggest</p>

<pre><code>for e in G.edges():
    G[e[0]][e[1]] = weights[e]
</code></pre>

python algorithm graph networkx edges