简体   繁体   中英

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. 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. The error message hints at this by saying that the length required is 2 and not the 3 that was provided. To fix this make the key be rows[0] and the associated value be 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:]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM