Reading CSV File and Deciding on a Data Structure
<p>I'm working with a rather basic CSV file depicting four cities and the distances between them. As such, the goal is to retrieve the information from said file, and use Python for further operations.</p>

<p><strong>Excel File</strong></p>

<p>The file is built up as follows in Excel:</p>

<p><a href="http://i.stack.imgur.com/MUx9J.png" rel="nofollow"><img src="http://i.stack.imgur.com/MUx9J.png" alt="cities.csv file"></a> </p>

<p><strong>CSV File</strong></p>

<p>When exported as CSV, the file is represented as follows:</p>

<pre><code>,OSL,CPH,LDN,TKO
OSL,0,2,4,10
CPH,2,0,2,9
LDN,4,2,0,12
TKO,10,9,12,0
</code></pre>

<p><strong>Getting the Cities</strong></p>

<p>Evidently, the first row contains all cities, as well as the first blank cell. I have done the following to retrieve the cities, excluding the blank cell: </p>

<pre><code>def get_cities(file):
  reader = csv.reader(file)

  cities = []

  row1 = next(reader)
  cities.extend(row1[1:]) #exclude first cell (blank)
  print cities
</code></pre>

<p>Yielding: </p>

<pre><code>['OSL', 'CPH', 'LDN', 'TKO']
</code></pre>

<p><strong>Mapping Cities and Distances between Them</strong></p>

<p>Having done so, I can now read the rest of the file, in order to retrieve the distances between the cities. </p>

<p><strong>However</strong>, I am finding it hard to come up with a good way of representing this information as a data structure. Optimally, I want to be able to check the distance between any two cities. </p>

<p>Any suggestions on how I can go about implementing this, would be highly appreciated. </p>

<p>That is, <strong>how can I best represent this information</strong> for easy distance lookup?</p>

<p>Use dict of dicts. This is not very memory efficient but is the simplest solution using built in python containers.</p>

<pre><code>    map = {'OSL' :
        {
            'OSL' : 0,
            'CPH' : 2,
            ...
        },
     'CPH' :
        {
            ...
        },
     ...
    }
</code></pre>

<p>Then you can look up the distance just like map['OSL']['CPH'].</p>

python csv data-structures types