How do I store this in an adjacency list for graphs in python?
<p>Suppose I have a text file containing this:</p>

<pre><code>0 1 4
0 2 3
1 4 7
5 3 8
</code></pre>

<p>The columns represent:</p>

<ol>
<li>a vertex</li>
<li>another vertex</li>
<li>the distance between these two vertices.  </li>
</ol>

<p>For example, in the first line in the text file, 4 is the distance between points 0 and 1.  </p>

<p>So how would I store the vertices and distances in an adjacency list in python?</p>

<p>Take a look at <a href="https://networkx.github.io/" rel="nofollow">NetworkX</a> library, it's awesome and easy to use.</p>

<p>From <a href="https://networkx.readthedocs.io/en/stable/reference/introduction.html#nodes-and-edges" rel="nofollow">the docs</a>, you can have edge attributes storing any value of interest - distance, in your case:</p>

<blockquote>
  <p>Edges often have data associated with them. <strong><em>Arbitrary data can associated with edges as an edge attribute. If the data is numeric and the intent is to represent a weighted graph then use the âweightâ keyword for the attribute.</em></strong> Some of the graph algorithms, such as Dijkstraâs shortest path algorithm, use this attribute name to get the weight for each edge.</p>
</blockquote>

<p>A possible implementation in your case would be:</p>

<pre><code>import networkx as nx

G=nx.Graph()

for line in file:
    a, b, w = map(int, line.strip().split(' '))
    G.add_edge(a, b, weight=w)
</code></pre>

python adjacency-list