AngryMan Studios
AngryMan Studios

Reputation: 13

How to work out an average from items within a dict.?

I am new to python so a simplified explanation would be much appreciated!

As of now I have a dictionary that looks like this:

names = {'Bob Smith': ['5', '6', '7', '5'], 'Fred Jones': ['8', '5', '7', '5', '9'], 'James Jackson': ['5','8','8','6','5']}

I need to do the following:

So far I have the following enclosed in an if statement:

if method == 2:
    for scores in names.items():
        score = scores[-1,-2,-3]
        average = sum(int(score)) / float(3)
        print(average)

I had a look at this thread too but I am still stuck.

Can anyone give me some pointers?

Upvotes: 0

Views: 207

Answers (3)

letsc
letsc

Reputation: 2567

names = {'Bob Smith': ['5', '6', '7', '5'], 'Fred Jones': ['8', '5', '7', '5', '9'], 'James Jackson': ['5','8','8','6','5']}

def avg(l):
    l = list(map(int,l))
    return sum(l[-3:])/3

avgs = []
for each in names.values():
    avgs.append(avg(each))

avgs.sort(reverse=True)
print avgs

Output:

[7, 6, 6]

Upvotes: 0

pppery
pppery

Reputation: 3804

Scores[-1,-2,-3] does not get the last three elements. It gets the element at the key (-1,-2,-3) in a dictionary, which will raise an error in the case of a list. Scores[-3:] would get the last three elements.

When getting the scores, you need to use names.values() instead of names.items()

The python string-to-integer conversions in the int type constructor are not smart enough to handle lists of strings, only individual strings. Using map(int,score) or int(i) for i in score would fix that.

The variable score is also an extremely poor choice of name for a list of elements.

Upvotes: 3

John La Rooy
John La Rooy

Reputation: 304137

In Python3.4+, there is a statistics module

>>> names = {'Bob Smith': ['5', '6', '7', '5'], 'Fred Jones': ['8', '5', '7', '5', '9'], 'James Jackson': ['5','8','8','6','5']}
>>> import statistics
>>> sorted((statistics.mean(map(int, x[-3:])) for x in names.values()), reverse=True)
[7.0, 6.333333333333333, 6.0]

Upvotes: 0

Related Questions