How can I create a dictionary from a list of k:v tuples returned from a SQL query?
<p>My SQL (sqlite3) query is along the lines of this:</p>

<pre><code>SELECT id, name FROM mytable;
</code></pre>

<p>This returns a ton of rows.  I would like to create a dictionary from these results, where I can lookup the name given an id.</p>

<p>Other answers I've found seem to create dictionaries based on SQL results, but they use the column label as the key -- I have no interest in that.</p>

<p>Example table:</p>

<pre><code>id    | name
------+--------
foo   | bar
baz   | foobar
</code></pre>

<p>Desired dict:</p>

<pre><code>{
    'foo': 'bar',
    'baz': 'foobar'
}
</code></pre>

<p>Suppose you get your sql query result in Python, something like</p>

<p><code>db_conn = sqlite3.connect('text.db')
cur = db_conn.cursor()
cur.execute('''select id, name from mytable''')</code></p>

<p>Then you can get all the query results in the return of <code>cur.fetchall()</code>.
The result will be a list of tuples, each tuple will be like (<em>id</em>,<em>name</em>).</p>

<p>Knowing this, then it is a piece of cake to transform it into an dictionary,just:</p>

<p><code>mydict = {}
for item in cur.fetchall():
    mydict[item[0]] = item[1]
</code></p>

python sql dictionary sqlite3