【发布时间】:2014-06-14 13:14:02
【问题描述】:
在this question 的帮助下,我从多个字典中生成了 csv(也可以阅读和编辑)。输出很简单
//Dictionary
key,value
key2,value2
//Dictionary2
key4, value4
key5, value5
我希望双反斜杠作为分隔符来创建新字典,但是每次调用 csv.reader(open("input.csv")) 都会通过行进行评估,所以我没有使用:
import csv
dict = {}
for key, val in csv.reader(open("input.csv")):
dict[key] = val
谢谢你帮我..
编辑:我制作了这段......很好的“代码”......如果你能检查一下,我会很高兴的:
#! /usr/bin/python
import csv
# list of dictionaries
l = []
# evalute throught csv
for row in csv.reader(open("test.csv")):
if row[0].startswith("//"):
# stripped "//" line is name for dictionary
n = row[0][2:]
# append stripped "//" line as name for dictionary
#debug
print n
l.append(n)
#debug print l[:]
elif len(row) == 2:
# debug
print "len(row) %s" % len(row)
# debug
print "row[:] %s" % row[:]
for key, val in row:
# print key,val
l[-1] = dic
dic = {}
dic[key] = val
# debug
for d in l:
print l
for key, value in d:
print key, value
不幸的是我得到了这个错误:
DictName
len(row) 2
row[:] ['key', ' value']
Traceback (most recent call last):
File "reader.py", line 31, in <module>
for key, val in row:
ValueError: too many values to unpack
【问题讨论】:
-
您的代码甚至不会尝试创建多个字典或查找
'//Dictionary',那么您为什么会期待任何不同呢?考虑遍历文件;每行的两种情况是什么,你应该在每一种情况下做什么? -
非常感谢@jonrsharpe,用原始代码更新了。
标签: python csv dictionary key key-value