1

Below is a sample of my dictionary:

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'}

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:

Croatia, 191

Cuba, 192

and I am using csv for this purpose:

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])

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

(see the image for reference: https://i.sstatic.net/F9dJu.jpg)

How do I solve this particular issue?

2 Answers 2

1

The docs cover how to handle encoding. Trying to encode individual elements does not, as you have seen, work out well.

Sign up to request clarification or add additional context in comments.

1 Comment

leveraging known python solutions is an excellent answer. The python 3 version of the docs
0

Well, I recommend you to use Pandas for your purpose.

import pandas as pd

country_name = dict.keys()
cnt = dict.values()
df = pd.DataFrame({'countryname':country_name,'count':cnt})
df.to_csv('result.csv',sep=',',encoding='utf-8')

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.