How can you write a dict lookup to a csv from mysql with python
<p>I write this csv from a mysql db tabel in this way:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>with open('outfile','w') as f:
    writer = csv.writer(f)
    for row in cursor.fetchall():
        writer.writerow(row)</code></pre>
</div>
</div>
</p>

<p>This will output this csv :</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>34,0.0,2016-04-07 14:51:16
8,59.08,2016-04-07 16:55:26
55,207.76,2016-04-08 06:24:42
37,247.14,2016-04-08 07:50:02
40,255.35,2016-04-08 07:58:51
49,480.26,2016-04-08 08:11:31</code></pre>
</div>
</div>
</p>

<p>And I have created this lookup dict like this :</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>machine_lookup = {}
for row in rows:
    machine_lookup[row['id']] = str(row['mr_machine_id'])</code></pre>
</div>
</div>
</p>

<p>This dict look like:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>{34: '1137', 8: '1125', 55: '1139', 37: '1140', 40: '1124', 40: '1138'}</code></pre>
</div>
</div>
</p>

<p>How I can edit my initial csv creator:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>with open('outfile','w') as f:
    writer = csv.writer(f)
    for row in cursor.fetchall():
        writer.writerow(row)</code></pre>
</div>
</div>
</p>

<p>to insert the first row as in the dict lookup in order to output my csv file to look like this :</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>1137,0.0,2016-04-07 14:51:16
1125,59.08,2016-04-07 16:55:26
1139,207.76,2016-04-08 06:24:42
1140,247.14,2016-04-08 07:50:02
1124,255.35,2016-04-08 07:58:51
1138,480.26,2016-04-08 08:11:31</code></pre>
</div>
</div>
</p>

<p>Since each row is a list. You can modify it in-place, or create a new list with the value you want to replace with.
for example:</p>

<pre><code>row[0] = value
</code></pre>

<p>In your code you can do like this.</p>

<pre><code>with open('outfile','w') as f:
writer = csv.writer(f)
for row in cursor.fetchall():
    row[0] = str(row['mr_machine_id'])
    writer.writerow(row)
</code></pre>

python mysql