How to convert convert csv to list of dictionaries (UTF-8)?
<p>I have a csv file (in.csv)</p>

<pre><code>col1, col2, col3
KapitÃ¤n, BÃ¶se, FÃ¼ller
...
</code></pre>

<p>and I want to create a list of dictionaries:</p>

<pre><code>a = [{'col1': 'KapitÃ¤n',  'col2': 'BÃ¶se', 'col3': 'FÃ¼ller'},{...}]
</code></pre>

<p>With Python 3 it's working with</p>

<pre><code>    import codecs
    with codecs.open('in.csv', encoding='utf-8') as f:
        a = [{k: v for k, v in row.items()}
            for row in csv.DictReader(f, skipinitialspace=True)]
    print(a)
</code></pre>

<p>(I've got this code from <a href="http://stackoverflow.com/questions/21572175/convert-csv-file-to-list-of-dictionaries">convert csv file to list of dictionaries</a>).</p>

<p>Unfortunately I need this for Python 2, but I don't come along with it. </p>

<p>I tried to understand <a href="https://docs.python.org/2.7/howto/unicode.html" rel="nofollow">https://docs.python.org/2.7/howto/unicode.html</a>, but I think I'm too stupid, because </p>

<pre><code>import codecs
f = codecs.open('in.csv', encoding='utf-8')
for line in f:
print repr(line) 
</code></pre>

<p>gives me</p>

<pre><code>u'col1,col2,col3\n'
u'K\xe4pten,B\xf6se,F\xfcller\n'
u'\n'
</code></pre>

<p>Do you have a solution for Python 2?</p>

<p>There is a similar problem solved here: <a href="http://stackoverflow.com/questions/6740918/creating-a-dictionary-from-a-csv-file">Creating a dictionary from a csv file?</a> But with the marked solution I get <code>('K\xc3\xa4pten', 'B\xc3\xb6se', 'F\xc3\xbcller')</code>. Maybe it's easy to edit it for getting <code>[{u'col1': u'K\xe4pten', u'col2': u'B\xf6se', u'col3': u'F\xfcller'}]</code>?</p>

<p>you can leverage the csv lib for the job.</p>

<pre><code>import csv

li_of_dicts = []
with open('in.csv', 'r') as infile:
     reader = csv.DictReader(infile, encoding='utf-8')
     for row in reader:
         li_of_dicts.append(row)
</code></pre>

python list python-2.7 csv dictionary