Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read CSV data and add it into dictionary

This is an empty Dictionary

d = {}

This is the csv file data

M, Max, Sporting, Football, Cricket
M, Jack, Sporting, Cricket, Tennis
M, Kevin, Sporting, Cricket, Basketball
M, Ben, Sporting, Football, Rugby

I tried to use the following code to append data from the csv to dictionary.

with open('example.csv', "r") as csvfile:
        csv_reader = csv.reader(csvfile)
        for row in csv_reader:
            if row:
                d.setdefault(row[0], {})[row[1]] = {row[2]: [row[3]]}

But it gives me an error:

d.setdefault(row[0], {})[row[1]] = {row[2]: [row[3]]}
IndexError: list index out of range

It there any way, i can add data from csv to the dictionary, in the form:

d = {'M': {'Max': {'Sporting': ['Football', 'Cricket']}, 'Jack': {'Sporting': ['Cricket', 'Tennis']}}}

I am new to this so help me.

like image 277
J.J Avatar asked Apr 30 '26 19:04

J.J


1 Answers

import csv

d={}
with open('JJ.csv', "r") as csvfile:
    csv_reader = csv.reader(csvfile)
    for row in csv_reader:
        if row:
            d.setdefault(row[0],{})[row[1]] = {row[2]: [row[3],row[4]]}
print(d)

{'M': {' Max': {' Sporting': [' Football', ' Cricket']}, ' Jack': {' Sporting': [' Cricket', ' Tennis']}, ' Kevin': {' Sporting': [' Cricket', ' Basketball']}, ' Ben': {' Sporting': [' Football', ' Rugby']}}}

To remove all the leading/trailing spaces in the output, you can use the below line instead. There might be a better way which I'm not sure as of now.

d.setdefault(row[0],{})[row[1].strip()] = {row[2].strip(): [row[3].strip(),row[4].strip()]}
like image 80
Van Peer Avatar answered May 02 '26 09:05

Van Peer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!