Codec error when writing Python dictionary into CSV
<p>Below is a sample of my dictionary:</p>

<pre><code>dict = {'Croatia': '191', 'Cuba': '192', 'CuraÃ§ao': '531', 
        'Cyprus': '196', 'Czechia': '203',  'Czechoslovakia': '200',
        "CÃ´te d'Ivoire": '384',  "Dem. People's Rep. of Korea": '408',
        'Dem. Rep. of the Congo': '180', 'Denmark': '208'}
</code></pre>

<p>My goal is to try to write the diction into a csv file so each row will have one key and one value, such as:</p>

<blockquote>
  <p>Croatia, 191 </p>
  
  <p>Cuba, 192</p>
</blockquote>

<p>and I am using <code>csv</code> for this purpose:</p>

<pre><code>import csv
with open('dict.csv', 'w') as csv_file:
writer = csv.writer(csv_file)
for key, value in dict.items():
   writer.writerow([key.encode('utf-8'), value])
</code></pre>

<p>when not using <code>key.encode('utf-8')</code>, Python gives the error of <strong>'ascii' codec can't encode character '\xf4' in position 1: ordinal not in range(128)</strong>, presumably cuased by <code>CÃ´te d'Ivoire</code> in the dictionary. However, even when a csv file can be successfully produced now, the csv file itself contains additional characters <code>b'countryname'</code> instead of <code>countryname</code>.</p>

<p>(see the image for reference: <a href="http://imgur.com/a/WH2gF" rel="nofollow">http://imgur.com/a/WH2gF</a>)</p>

<p>How do I solve this particular issue?</p>

<p><a href="https://docs.python.org/2/library/csv.html" rel="nofollow">The docs</a> cover how to handle encoding.  Trying to encode individual elements does not, as you have seen, work out well.</p>

python csv dictionary