Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 4561734
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 21, 20262026-05-21T18:07:01+00:00 2026-05-21T18:07:01+00:00

I have a list of dictionaries containing unicode strings. csv.DictWriter can write a list

  • 0
  1. I have a list of dictionaries containing unicode strings.
  2. csv.DictWriter can write a list of dictionaries into a CSV file.
  3. I want the CSV file to be encoded in UTF8.
  4. The csv module cannot handle converting unicode strings into UTF8.
  5. The csv module documentation has an example for converting everything to UTF8:

    def utf_8_encoder(unicode_csv_data):
        for line in unicode_csv_data:
            yield line.encode('utf-8')
    
  6. It also has a UnicodeWriter class.

But… how do I make DictWriter work with these? Wouldn’t they have to inject themselves in the middle of it, to catch the disassembled dictionaries and encode them before it writes them to the file? I don’t get it.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-21T18:07:02+00:00Added an answer on May 21, 2026 at 6:07 pm

    UPDATE: The 3rd party unicodecsv module implements this 7-year old answer for you. Example below this code. There’s also a Python 3 solution that doesn’t required a 3rd party module.

    Original Python 2 Answer

    If using Python 2.7 or later, use a dict comprehension to remap the dictionary to utf-8 before passing to DictWriter:

    # coding: utf-8
    import csv
    D = {'name':u'马克','pinyin':u'mǎkè'}
    f = open('out.csv','wb')
    f.write(u'\ufeff'.encode('utf8')) # BOM (optional...Excel needs it to open UTF-8 file properly)
    w = csv.DictWriter(f,sorted(D.keys()))
    w.writeheader()
    w.writerow({k:v.encode('utf8') for k,v in D.items()})
    f.close()
    

    You can use this idea to update UnicodeWriter to DictUnicodeWriter:

    # coding: utf-8
    import csv
    import cStringIO
    import codecs
    
    class DictUnicodeWriter(object):
    
        def __init__(self, f, fieldnames, dialect=csv.excel, encoding="utf-8", **kwds):
            # Redirect output to a queue
            self.queue = cStringIO.StringIO()
            self.writer = csv.DictWriter(self.queue, fieldnames, dialect=dialect, **kwds)
            self.stream = f
            self.encoder = codecs.getincrementalencoder(encoding)()
    
        def writerow(self, D):
            self.writer.writerow({k:v.encode("utf-8") for k,v in D.items()})
            # Fetch UTF-8 output from the queue ...
            data = self.queue.getvalue()
            data = data.decode("utf-8")
            # ... and reencode it into the target encoding
            data = self.encoder.encode(data)
            # write to the target stream
            self.stream.write(data)
            # empty queue
            self.queue.truncate(0)
    
        def writerows(self, rows):
            for D in rows:
                self.writerow(D)
    
        def writeheader(self):
            self.writer.writeheader()
    
    D1 = {'name':u'马克','pinyin':u'Mǎkè'}
    D2 = {'name':u'美国','pinyin':u'Měiguó'}
    f = open('out.csv','wb')
    f.write(u'\ufeff'.encode('utf8')) # BOM (optional...Excel needs it to open UTF-8 file properly)
    w = DictUnicodeWriter(f,sorted(D.keys()))
    w.writeheader()
    w.writerows([D1,D2])
    f.close()
    

    Python 2 unicodecsv Example:

    # coding: utf-8
    import unicodecsv as csv
    
    D = {u'name':u'马克',u'pinyin':u'mǎkè'}
    
    with open('out.csv','wb') as f:
        w = csv.DictWriter(f,fieldnames=sorted(D.keys()),encoding='utf-8-sig')
        w.writeheader()
        w.writerow(D)
    

    Python 3:

    Additionally, Python 3’s built-in csv module supports Unicode natively:

    # coding: utf-8
    import csv
    
    D = {u'name':u'马克',u'pinyin':u'mǎkè'}
    
    # Use newline='' instead of 'wb' in Python 3.
    with open('out.csv','w',encoding='utf-8-sig',newline='') as f:
        w = csv.DictWriter(f,fieldnames=sorted(D.keys()))
        w.writeheader()
        w.writerow(D)
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have a list of dictionaries, and I want to use it to create
If I have List<String> text how can I create a sub-list of all continious
I have an List and I'd like to wrap it into an IQueryable. Is
I have a list of bean objects passed into my JSP page, and one
I have a list of integers, List<Integer> and I'd like to convert all the
I have a List of Foo. Foo has a string property named Bar. I'd
I have a list of 2-item tuples and I'd like to convert them to
I have a List<int> and a List<customObject> . The customObject class has an ID
I have a list, each item of which has several things in it, including
I have a list of more than 15 thousand latitude and longitude coordinates. Given

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.