[英]Python 2.7: ValueError using csv to create a dictionary
I am trying to read a 3 column csv into a dictionary with the code below. 我正在尝试使用下面的代码将3列csv读入字典。 The 1st column is the unique identifier, and the following 2 are information related.
第一列是唯一标识符,而第二列是相关信息。
d = dict()
with open('filemane.csv', 'r') as infile:
reader = csv.reader(infile)
mydict = dict((rows[0:3]) for rows in reader)
print mydict
When I run this code I get this error: 当我运行此代码时,出现以下错误:
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
Dictionaries need to get a key along with a value. 字典需要获得一个键和一个值。 When you have
当你有
mydict = dict((rows[0:3]) for rows in reader)
^^^^^^^^^
ambiguous
You are passing in a list that is of length 3 which is not of the length 2 (key, value)
format that is expected. 您要传递的列表的长度为3,而不是预期的长度2
(key, value)
格式。 The error message hints at this by saying that the length required is 2 and not the 3 that was provided. 错误消息暗示了这一点,要求的长度为2,而不是所提供的3。 To fix this make the key be
rows[0]
and the associated value be rows[1:3]
: 要解决此问题,请将键设置为
rows[0]
,并将关联值设置为rows[1:3]
:
mydict = dict((rows[0], rows[1:3]) for rows in reader)
^^^^^^ ^^^^^^^^^
key value
You can do something along the lines of: 您可以按照以下方式进行操作:
with open('filemane.csv', 'r') as infile:
reader = csv.reader(infield)
d={row[0]:row[1:] for row in reader}
Or, 要么,
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.