NetworkX: how to properly create a dictionary of edge lengths?
<p>Say I have a regular grid network made of <code>10x10</code> nodes which I create like this:</p>

<pre><code>import networkx as nx
from pylab import *
import matplotlib.pyplot as plt
%pylab inline

ncols=10 

N=10 #Nodes per side
G=nx.grid_2d_graph(N,N)
labels = dict( ((i,j), i + (N-1-j) * N ) for i, j in G.nodes() )
nx.relabel_nodes(G,labels,False)
inds=labels.keys()
vals=labels.values()
inds=[(N-j-1,N-i-1) for i,j in inds]
posk=dict(zip(vals,inds))
nx.draw_networkx(G, pos=posk, with_labels=True, node_size = 150, node_color='blue',font_size=10)
plt.axis('off')
plt.title('Grid')
plt.show()
</code></pre>

<p>Now say I want to create a dictionary which stores, for each edge, its length. This is the intended outcome:</p>

<pre><code>d={(0,1): 3.4, (0,2): 1.7, ...}
</code></pre>

<p>And this is how I try to get to that point:</p>

<pre><code>from math import sqrt

lengths={G.edges(): math.sqrt((x-a)**2 + (y-b)**2) for (x,y),(a,b) in G.edges()}
</code></pre>

<p>But there clearly is something wrong as I get the following error message:</p>

<pre><code>---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
&lt;ipython-input-7-c73c212f0d7f&gt; in &lt;module&gt;()
      2 from math import sqrt
      3 
----&gt; 4 lengths={G.edges(): math.sqrt((x-a)**2 + (y-b)**2) for (x,y),(a,b) in G.edges()}
      5 
      6 

&lt;ipython-input-7-c73c212f0d7f&gt; in &lt;dictcomp&gt;(***failed resolving arguments***)
      2 from math import sqrt
      3 
----&gt; 4 lengths={G.edges(): math.sqrt((x-a)**2 + (y-b)**2) for (x,y),(a,b) in G.edges()}
      5 
      6 

TypeError: 'int' object is not iterable
</code></pre>

<p><strong>What am I missing?</strong></p>

<p>There is a lot going wrong in the last line, first and foremost that G.edges() is an iterator and not a valid dictionary key, and secondly, that G.edges() really just yields the edges, not the positions of the nodes.</p>

<p>This is what you want instead: </p>

<pre><code>lengths = dict()
for source, target in G.edges():
    x1, y1 = posk[source]
    x2, y2 = posk[target]
    lengths[(source, target)] = math.sqrt((x2-x1)**2 + (y2-y1)**2)
</code></pre>

python dictionary networkx