Read cvs file to Dictionary python
<p>Please, I need to read CSV file and convert the result to a dictionary.</p>

<p>File input:</p>

<p><a href="https://i.stack.imgur.com/4h26Q.png" rel="nofollow"><img src="https://i.stack.imgur.com/4h26Q.png" alt="enter image description here"></a></p>

<p>The required object after reading like below:</p>

<pre><code>defaultdict(&lt;type 'dict'&gt;, {âBookâ: {âBookâ: 1.0, âAfnanâ: 0, âLocationâ: 0, âLoveâ: 0}, âAfnanâ: {âBookâ: 0, âAfnanâ: 1.0, âLocationâ: 0.71, âLoveâ: 0}, âLocationâ: {âBookâ: 0, 'Afnanâ: 0.71, âLocationâ: 1.0, âLoveâ: 0}, âLoveâ: {âBookâ: 0, âAfnanâ: 0, âLocationâ: 0, âLoveâ: 1.0}})
</code></pre>

<p>I write below code but is not working as what I want. Please help.</p>

<pre><code>reader = unicode_csv_reader(open('cos3.csv'))
x=list(reader)
for i in x:
    if isinstance(i,float):
        arr=np.array(x).astype('float')
    else:
        arr=np.array(x).astype('string')
d=defaultdict(dict)
for a in arr:
    for b in arr:
        d[a][b]=arr(a)
</code></pre>

<p>I always use <code>csv.DictReader</code> and then build the dictionary in the format you want like so:</p>

<p><a href="https://i.stack.imgur.com/weNmx.png" rel="nofollow"><img src="https://i.stack.imgur.com/weNmx.png" alt="enter image description here"></a></p>

<pre><code>import csv
import os
cwd = os.getcwd()


d_out = {}
with open(cwd+'\\example.csv', 'rb') as file_in:
    reader = csv.DictReader(file_in, restkey=None, restval=None, dialect='excel')
    for row in reader:
        d_out.setdefault(row['Key'], {'Book':row['Book'], 'Afnan':row['Afnan'], 'Location':row['Location'], 'Love':row['Love']})


print d_out
</code></pre>

<p>Hope this helps!</p>

python csv dictionary