Home > database >  Creating a dictionary of dictionaries from a CSV file
Creating a dictionary of dictionaries from a CSV file

Time:01-30

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

CodePudding user response:

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))
  • Related