python-3.x - 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
解决方案
嗨,这是您要实现的目标吗?
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'))
推荐阅读
- arrays - 如何在波形中查看 SystemVerilog 动态数组
- huawei-mobile-services - Codelab基于Health Kit开发的应用程序读取活动数据并报错怎么办?
- flutter - 如何在类中定位 Text/TextSpan
- html - 使用 role = "listbox" 输入元素是否有效?
- ibm-watson - 使用 ibm-watson-speech-to-text 获取音频文件
- python-3.7 - 如何使用 python 列出 gcp 项目中的所有 vpc_access_connector
- jquery - 使用 `jQuery 验证` 和 `Select2` 显示和隐藏成功和错误,符合`bootstrap4`
- laravel - laravel PresenceChannel 加入不起作用
- python-3.x - 如何在 ruamel yaml 中定义新字典的样式?
- database - V$SESSION 表中 MACHINE 和 TERMINAL 的区别