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>You can loop over the rows (the <a href="https://docs.python.org/3/library/sqlite3.html#module-sqlite3" rel="nofollow">result cursor is iterable</a>), <a href="https://docs.python.org/3/tutorial/datastructures.html#tuples-and-sequences" rel="nofollow">unpack</a> the key and value, then assemble the result using a <a href="https://docs.python.org/3/tutorial/datastructures.html#dictionaries" rel="nofollow">dict comprehension</a>:</p>

<pre><code>desired_dict = {k:v for k, v in c.execute('SELECT id, name FROM MyTable')}
</code></pre>

<p>I like using dict comprehensions because I can do additional processing to the results before adding to the dictionary (for example changing case, converting to decimal or datetime, etc).</p>

<p>That said, if you want to go directly to the dict, <em>ozgur</em> has the shorter, faster way which is to call <a href="https://docs.python.org/3/library/functions.html#func-dict" rel="nofollow"><em>dict()</em></a> directly:</p>

<pre><code>desired_dict = dict(c.execute('SELECT id, name FROM MyTable'))
</code></pre>

<p>Here's an actual sample session demonstrating the process start to finish:</p>

<pre><code>&gt;&gt;&gt; import sqlite3
&gt;&gt;&gt; c = sqlite3.connect('tmp.db')
&gt;&gt;&gt; c.execute('CREATE TABLE MyTable (id text, name text)')
&lt;sqlite3.Cursor object at 0x106227f80&gt;
&gt;&gt;&gt; c.execute("INSERT INTO MyTable VALUES ('abc', 'Alpha')")
&lt;sqlite3.Cursor object at 0x106283810&gt;
&gt;&gt;&gt; c.execute("INSERT INTO MyTable VALUES ('def', 'Beta')")
&lt;sqlite3.Cursor object at 0x106227f80&gt;
&gt;&gt;&gt; c.execute("INSERT INTO MyTable VALUES ('ghi', 'Gamma')")
&lt;sqlite3.Cursor object at 0x106283810&gt;
&gt;&gt;&gt; c.commit()
&gt;&gt;&gt; c.close()
&gt;&gt;&gt; 
&gt;&gt;&gt; c = sqlite3.connect('tmp.db')
&gt;&gt;&gt; {k:v for k, v in c.execute('SELECT id, name FROM MyTable')}
{'ghi': 'Gamma', 'def': 'Beta', 'abc': 'Alpha'}
</code></pre>

python sql dictionary sqlite3