user2471181
user2471181

Reputation: 163

A 'too many values to unpack' error in python

import pylab as pl

data = """AP 10
AA 20
AB 30
BB 40
BC 40
CC 30
CD 20
DD 10"""

grades = []
number = []

for line in data.split("/n"):
     x, y = line.split()
     grades.append(x)
     number.append(int(y))       
fig = pl.figure()
ax=fig.add_subplot(1,1,1)
ax.bar(grades,number)
p.show()

This is my code, i wish to make a bar graph, from the data. Initially when I run my code, I was getting an indentation error, in line 17, after adding a space to all the entire for block, I started getting this 'too many values to unpack error', in line 16. I am new to python, and I don't know how to proceed now.

Upvotes: 3

Views: 1642

Answers (4)

mgilson
mgilson

Reputation: 309919

For a fun alternative, rather than using the splitlines method as proposed by others, You could also use a StringIO object here:

>>> data = """AP 10
... AA 20
... AB 30
... BB 40
... BC 40
... CC 30
... CD 20
... DD 10"""
>>> import cStringIO as StringIO
>>> filelike = StringIO.StringIO(data)
>>> for line in filelike:
...     print line.split()
... 
['AP', '10']
['AA', '20']
['AB', '30']
['BB', '40']
['BC', '40']
['CC', '30']
['CD', '20']
['DD', '10']

Upvotes: 1

Martijn Pieters
Martijn Pieters

Reputation: 1121844

You have a line that does not have two items on it:

 x, y = line.split()

did not split to two elements and that throws the error. Most likely because you are not splitting your data variable properly and have the whole text as one long text. /n does not occur in your data data.

Use .splitlines() instead:

for line in data.splitlines():
     x, y = line.split()

Upvotes: 4

BergmannF
BergmannF

Reputation: 10255

The problem is that your for-loop is splitting at the wrong token (/n) instead of \n.

But when you only want to split the newlines there actually is a splitlines()-method on strings that does just that: you should actually use this method, because it will handle different newline delimiters between *nix and Windows as well (*nix systems typically denote newlines via \r\n, whereas Windows uses \n and the old Mac OS uses \r: check the Python documentation for more information)

Your error occurs on the next line: due to the fact that the string was not split into lines your whole string will now be split on the whitespace, which will produces many more values than the 2 you try to assign to a tuple.

Upvotes: 4

jamylak
jamylak

Reputation: 133554

for line in data.split("/n")

should be

for line in data.split("\n")

or even better:

for line in data.splitlines()

Upvotes: 3

Related Questions