Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Creating a dictionary of dictionaries from a CSV file

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading