首页 / PYTHON / python导入csv列表
python导入csv列表
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了python导入csv列表,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1784字,纯文字阅读大概需要3分钟。
内容图文
![python导入csv列表](/upload/InfoBanner/zyjiaocheng/816/851d3275a82b48bdad220f27c2667ff7.jpg)
我想在CSV中将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
解决方法:
这有帮助吗?
import StringIO
import csv
csvfile = StringIO.StringIO("""queryInclude,yahoo,value1
queryInclude,yahoo,value2
queryInclude,yahoo,value3
queryExclude,yahoo,value4
queryExclude,yahoo,value5
queryInclude,google,value6
queryExclude,google,value7""")
reader = csv.reader(csvfile, delimiter=',', quotechar='|')
dict1={}
for row in reader:
key1, provider, value1 = row
if not dict1.has_key(key1):
dict1[key1] = {}
if not dict1[key1].has_key(provider):
dict1[key1][provider] = []
dict1[key1][provider].append(value1)
内容总结
以上是互联网集市为您收集整理的python导入csv列表全部内容,希望文章能够帮你解决python导入csv列表所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。