首页 > 解决方案 > Python对带有字符串键和列表值的字典的理解

问题描述

我正在寻找理解来阅读 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

标签: python-3.xdictionarydictionary-comprehension

解决方案


嗨,这是您要实现的目标吗?

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

推荐阅读