How to store mySQL query as python dictionary and call later in script?
<p>I have a table called "<strong>uid</strong>" which has two fields, <strong>rfid</strong> and <strong>empid</strong>:</p>

<ul>
<li><strong>EXAMPLE RECORD 1</strong> rfid = 88 999 33 555 empid = 1 </li>
<li><strong>EXAMPLE RECORD 2</strong> rfid    = 64 344 77 222 empid = 2</li>
</ul>

<p>I would like to run a query which stores all of these values in a python dictionary, and allows me to set the rfid number as a variable (MyRFID) to be called later in the script:</p>

<pre><code>db = MySQLdb.connect("MyIp", "MyUser", "MyPass", "MyDB", cursorclass=MySQLdb.cursors.DictCursor)
curs=db.cursor()
curs.execute("""SELECT number, empid FROM rfid """)
</code></pre>

<p>So that later in the code I can check to see if I get a match from an existing variable:</p>

<pre><code>if MyVariable == MyRFID:
    #Create new record for that empid
</code></pre>

<p>I think you're looking for the fetchall method.  After you call </p>

<p><code>cur.execute("""SELECT number, empid FROM rfid """)</code></p>

<p>you would do:</p>

<p><code>rows = cur.fetchall()</code></p>

<p>and then rows would contain a list of tuples.  If you specifically need it to be a dictionary, you could just do <code>dict(rows)</code> in this example but that only works because your query happens to return two columns.  If it was more than two columns you would need something like:</p>

<p><code>rows_dict = dict([ k[0], k[1:]) for k in rows])</code></p>

<p>(see: <a href="http://stackoverflow.com/questions/14263494/converting-list-of-3-element-tuple-to-dictionary">Converting List of 3 Element Tuple to Dictionary</a>)</p>

<p>If the dictionary you were imagining had column names as keys you need to look at DictCursor (<a href="http://stackoverflow.com/questions/2180226/python-use-mysqldb-to-import-a-mysql-table-as-a-dictionary">Python: use mysqldb to import a MySQL table as a dictionary?</a>).</p>

python mysql dictionary