我正在寻找阅读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发布于 2019-09-24 21:19:59
嗨,这就是你想要实现的吗?
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'))https://stackoverflow.com/questions/58080942
复制相似问题