Avishek
Avishek

Reputation: 430

Python comprehension for dictionary with String key and List values

I am looking for comprehension to read a csv and create a dictionary where key is string and value is list

the csv looks like

fruit,Apple
vegetable,Onion
fruit,Banana
fruit,Mango
vegetable,Potato

my output should be like

{'fruit':['Apple','Banana','Mango'],'vegetable':['Onion','Potato']}

I am looking for dictionary comprehension to do that , I tried like

def readCsv(filename):
    with open(filename) as csvfile:
        readCSV = csv.reader(csvfile, delimiter='\t')
        dicttest={row[1]:[].append(row[2]) for row in readCSV}
        return dicttest

Upvotes: 0

Views: 65

Answers (1)

elomat
elomat

Reputation: 139

Hi Is this what you are trying to achieve?

import csv
def readCsv(filename):
    d = {}
    with open(filename) as csvfile:
        readCSV = csv.reader(csvfile, delimiter='\t')

        for row in readCSV:
            d.setdefault(row[0], []).append(row[1])
    return d

print(readCsv('test.csv'))

Upvotes: 3

Related Questions