Help with Python dictionary iteration

Hey guys. I recently started learning the basics of Python here, and I’m having a problem with a little dictionary experiment.

Here is the dictionary:

#key is player name, value is points scored
players = {"Steve Nash": [14, 9, 5, 22], "Michael Jordan": [20, 21, 24, 26], "Kevin Durant": [40, 32, 41, 25], "Dirk Nowitzki": [26, 21, 25, 38], "Hakeem Olajuwan": [33, 41, 38, 21]}

I am trying to iterate over the dictionary to return average points for each player. I’ve tried various things with varying, undesired results, including:

def avg_pts(team):
    sum = 0

    for key, value in team.items():
        for number in value:
            sum += number
            avg = sum / len(value)

        print(key, avg)

#Returns: Steve Nash 12.5
Michael Jordan 35.25
Kevin Durant 69.75
Dirk Nowitzki 97.25
Hakeem Olajuwan 130.5

I know what is wrong with the above code, but I’m missing some key knowledge about how to isolate each player’s scores from the others’. I’m not even sure if I’m approaching it even remotely in the right way.

Any help is greatly appreciated!

use print to write out messages showing what is being done so that you can observe

you can also make a function that only deals with one entry, which you could apply to each entry – if you do something many times then sometimes it’s easier to implement how to do it once and then scale it up with separate code


Thanks for the advice. I’ve changed direction with it a bit and making some progress now :slight_smile: