Search code examples
pythonappendtuplespython-idle

Python Write to Tuple Error with append



I'm practicing Python 3.3.2 and I would like to practice the append technique to a tuple.
I have a text file named user_scores.txt. and it consists of scores from people in my workplace that they have submitted for a mathematical problem. They have submitted different answers that they could produce. The file is shown below (Alex only submitted two):

Alex, 35, 39
Daniel, 34, 35, 36 
Richard, 21, 23, 24

I am trying to write these scores to a tuple in this form:

Name:Score, Score, Score.

So for example:
Alex:35, 39,
Daniel:34, 35, 36

I have attempted this with the code below, but it does not work as it returns the error underneath:

user_scores = []

with open('user_scores.txt') as f:
    for line in f:
        worker,score = line.strip().replace("\n","").split(",")
        user_scores[worker].append(int(score))

The error:

ValueError: too many values to unpack (expected 2)

What is the fix? Is my block of code completely wrong or what?

Thanks, Dora.


Solution

  • First let's fix your data structure. You're referring to each score-tuple by test-taker name. Referring to values by a key (rather than by an index) is done using a dictionary.

    user_scores = dict() # or = {}. Same difference.
    

    Then we know two things:

    1. That the first item each line will be the name of the test-taker
    2. That there will be some number of scores thereafter, which will all be integers

    So we can iterate through the file like this:

    with open('path/to/file.txt') as infile:
        for line in infile:
            name, *scores = line.strip().split(',')
    

    The glob there * instructs Python that there will be lots of these, so make a tuple of equivalent size. a, *b = (1, 2, 3, 4, 5) makes a = 1; b = (2, 3, 4, 5). Now it's an easy thing to assign your values!

    user_scores[name] = [int(score) for score in scores]
    

    Note that this creates a list, not a tuple, but that's LIKELY what you want anyway. Tuples indicate that the position of each element isn't just important but it HAS MEANING. This is easily explained by a point in the 2-D coordinate plane expressed as an ordered pair

    #x, y
    (1, 10)
    

    is much different from

    #x , y
    (10, 1)
    

    In a list, it might be important that the list keep its order, but all of the elements MEAN the same thing. That's your use case here -- they're all scores, and you might want to correlate that each test-taker improved over time, but ultimately if a test score got moved to a different position, it doesn't change the fact that it's still a test score.