2

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
2
  • @shuttle87 thank you! I'm new and learning. I see now you declare the Key, and then the Values. Commented Nov 11, 2015 at 18:18
  • If my answer solved your problem then you can mark it as accepted with the green checkbox. Commented Nov 11, 2015 at 18:26

2 Answers 2

2

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
Sign up to request clarification or add additional context in comments.

Comments

2

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:]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.