【发布时间】:2012-12-31 13:36:51
【问题描述】:
我想在 python 中将 CSV 导入到多个字典中
queryInclude,yahoo,value1
queryInclude,yahoo,value2
queryInclude,yahoo,value3
queryExclude,yahoo,value4
queryExclude,yahoo,value5
queryInclude,google,value6
queryExclude,google,value7
我的理想结果应该是 row[0]=dictionary、row[1]=key 和 row[2]=value 或值列表
queryInclude = {
"yahoo": ["value1", "value2", "value3"],
"google": ["value6"] }
queryExclude = {
"yahoo": ["value4", "value5"],
"google": ["value7"] }
这是我的代码:
import csv
queryList=[]
queryDict={}
with open('dictionary.csv') as csvfile:
reader = csv.reader(csvfile, delimiter=',', quotechar='|')
for row in reader:
queryDict[row[1]] = queryList.append(row[2])
print queryDict
{'yahoo': None}
{'yahoo': None}
{'yahoo': None}
{'yahoo': None}
{'yahoo': None}
{'google': None, 'yahoo': None}
{'google': None, 'yahoo': None}
如果需要,我可以灵活地更改 CSV 格式。我上面发布的理想结果是我已经硬编码到我的应用程序中的结果。我正在努力让未来添加更多价值变得更容易。我已经花了很多时间研究这个问题,如果我取得更多进展,我会继续更新。我的思维过程看起来像这样......不确定我离理解如何在遍历 CSV 行时构建循环和组合相似值有多接近......
for row in reader:
where row[0] = queryInclude:
create a dictionary combining keys into a list of values
where row[0] = queryExclude:
create a dictionary combining keys into a list of values
【问题讨论】:
标签: python csv dictionary import