Creating a dictionary of dictionaries from a CSV file

Question:

I am trying to create a dictionary of dictionaries in Python from a CSV file, the file looks something like this:

Column 1 Column 2 Column 3
A flower 12
A sun 13
B cloud 14
B water 34
C rock 12

And I am trying to get a dictionary of dictionaries that looks like this:

    dict = {
        'A': {'flower': 12, 'sun': 13},
        'B': {'cloud': 14, 'water': 34},
        'C': {'rock': 12}
                   }

The code I tried so far is as follows:

import csv 
with open('file.csv', 'r') as csvFile:  
    rows=csv.reader(csvFile) 
    d=dict()     
    for row in rows: 
        head,tail=row[0], row[1:] 
        d[head]=dict(zip(tail[0:], tail[1:])) 
    print(d) 

but it’s not working well as I am getting this result:

dict = {
        'A': {'sun': 13},
        'B': {'water': 34},
        'C': {'rock': 12}
                   }
Asked By: Lama

||

Answers:

You need to update your d[head] every iteration, not replace it:

import csv 
with open('file.csv', 'r') as csvFile:  
    rows=csv.reader(csvFile) 
    d=dict()     
    for row in rows:
        head,name,value=row[0], row[1], row[2]
        if head not in d:
            d[head]= {} # {} is like dict() but faster
        d[head][name] = value
    print(d)

Or with defaultdict to be more concise:

import csv
from collections import defaultdict

with open('file.csv', 'r') as csvFile:  
    rows=csv.reader(csvFile) 
    d = defaultdict(dict)
    for row in rows:
        head,name,value=row[0], row[1], row[2]
        d[head][name] = value
    print(d) # or print(dict(d))
Answered By: kosciej16
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.