[英]Python 2.7: ValueError using csv to create a dictionary
我正在尝试使用下面的代码将3列csv读入字典。 第一列是唯一标识符,而第二列是相关信息。
d = dict()
with open('filemane.csv', 'r') as infile:
reader = csv.reader(infile)
mydict = dict((rows[0:3]) for rows in reader)
print mydict
当我运行此代码时,出现以下错误:
Traceback (most recent call last):
File "commissionsecurity.py", line 34, in <module>
mydict = dict((rows[0:3]) for rows in reader)
ValueError: dictionary update sequence element #0 has length 3; 2 is required
字典需要获得一个键和一个值。 当你有
mydict = dict((rows[0:3]) for rows in reader)
^^^^^^^^^
ambiguous
您要传递的列表的长度为3,而不是预期的长度2 (key, value)
格式。 错误消息暗示了这一点,要求的长度为2,而不是所提供的3。 要解决此问题,请将键设置为rows[0]
,并将关联值设置为rows[1:3]
:
mydict = dict((rows[0], rows[1:3]) for rows in reader)
^^^^^^ ^^^^^^^^^
key value
您可以按照以下方式进行操作:
with open('filemane.csv', 'r') as infile:
reader = csv.reader(infield)
d={row[0]:row[1:] for row in reader}
要么,
d=dict()
with open('filemane.csv', 'r') as infile:
reader = csv.reader(infield)
for row in reader:
d[row[0]]=row[1:]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.