charlotte knight
charlotte knight

Reputation: 11

python error need more than one value to unpack

i have read all the other questions asked about this python error and none of them are helping me, i am a beginner on python and really need help. i have to find the average of some students results from a file and it comes up with the error more then one value to unpack on lines 4 and 7

fileName = classChoice + ".txt" # generate the name of the file to read
with open (fileName) as f:
    for line in f.readlines():
        userName,score= line.split(' : ')
        scores[userName].append(int(score))
        total=0
    for (userName, score )in fileName:
        total=total+score
        average= total/len(fileName)
        print("the average is ", average)

Upvotes: 0

Views: 235

Answers (2)

poke
poke

Reputation: 388443

You have two issues in your code.

userName,score= line.split(' : ')

This will fail, if the line does not contain ' : '. For example, a line with 'Foo: 12' will already fail because there is no space before the colon. You’re better off splitting by the colon only, and then trimming whitespace from the values:

userName, score = line.split(':')
scores[userName.strip()].append(int(score.strip()))

The other issue is with the following line:

for (userName, score )in fileName:

fileName is a string containing the file name of the file you opened before and read from. What you probably want to do is iterate through the dictionary scores. Note that you collected individual score values for each user, so the dictionary values are actually score lists. So you need to iterate through those again:

for userName, userScores in scores.items():
    total = 0
    for score in userScores:
        total += score
    average = total / len(userScores)
    print("the average for", userName, "is", average)

Upvotes: 1

Quentin Roy
Quentin Roy

Reputation: 7887

The notation a, b = l will only work if len(l) == 2 (for a, b, c = l, for len(l) == 3 and so on).

Here, it looks like line.split(' : ') gives you a list containing only one value so it cannot be unpacked.

In the case of a string like fileName, the unpacking will happens at the character level. Here, fileName contains definitely more than 2 char (it is at least ".txt" if classChoice is empty) so it cannot work. Here you should get ValueError: too many values to unpack.

Upvotes: 0

Related Questions