带有字符串键和列表值的字典的Python理解

时间:2019-09-24 13:02:01

标签: python-3.x dictionary dictionary-comprehension

我正在寻找一种理解方法,以读取csv并创建键为字符串,值为列表的字典

csv看起来像

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

我的输出应类似于

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

我正在寻找字典理解来做到这一点,我尝试过

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

1 个答案:

答案 0 :(得分:3)

嗨,这是您要达到的目标吗?

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'))