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>Nested dictionaries are a natural way to represent adjacency lists. Dictionaries are convenient in this situation because they can represent sparse mappings better than lists, and allow efficient lookups.</p>

<pre><code>adjacency_list = {}
for line in open(file):
    from, to, weight = map(int, line.split())
    adjacency_list.setdefault(from, {})[to] = weight
    adjacency_list.setdefault(to, {})[from] = weight  # for undircted graph add reverse edges
</code></pre>

<p>To get the weight of an edge between node <code>i</code> and <code>j</code>, you'd lookup <code>adjacency_list.get(i, {}).get(j)</code> (which will return <code>None</code> if the edge doesn't exist).</p>

<p>If you didn't want to deal with <code>setdefault</code> and <code>get</code>, you might want to  use a <code>defaultdict</code> for at least the top-level dictionary. If you initialize with <code>adjacency_list = defaultdict(dict)</code>, then setting the weights would just be <code>adjacency_list[from][to] = weight</code> (the inner dictionaries will be created automatically whenever they're needed).</p>

python adjacency-list