[英]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.