Convert text grid to nested dictionary in python
<p>Imagine a grid in a text file like this:</p>

<pre><code>  A  B  C
A 0  1  2
B 3  0  5
C 6  7  0
</code></pre>

<p>What would be the nicest way to convert this into a dictionary in python like the following:</p>

<pre><code>{
  'A': {'A': 0, 'B':3, 'C':6},
  'B': {'A': 1, 'B':0, 'C':7},
  'B': {'A': 2, 'B':5, 'C':0}
}
</code></pre>

<p>So I can access cells with:</p>

<pre><code>matrix['A']['B'] # 3
</code></pre>

<p>I currently do have some very rough code (please don't judge me too harshly):</p>

<pre><code>matrix = {}
f = open(filepath, 'r')
lines = f.readlines()
keys = lines[0].split()

for key in keys:
    matrix[key] = {}

for line in lines[1:]:
    chars = line.split()
    key_a = chars[0]
    for i, c in enumerate(chars[1:]):
        key_b = keys[i-1]
        matrix[key_a][key_b] = int(c)

print matrix

# Outputs {'A': {'A': 1, 'C': 0, 'B': 2}, 'C': {'A': 7, 'C': 6, 'B': 0}, 'B': {'A': 0, 'C': 3, 'B': 5}}
</code></pre>

<p>Whilst this isn't wrong, I've spent a long time away from python, is there a nicer way? Perhaps a nested dictionary isn't actually the best way?</p>

<p><strong>UPDATES</strong>:</p>

<ol>
<li>Unfortunately I need to do this in vanilla python so using external libraries (which believe me I would love) isn't possible</li>
<li>Updated my sample code form pseudocode to actual code. Hangs head in shame.</li>
</ol>
