SaricS
SaricS

Reputation: 13

How can I print the mean of key values of a dictionary in Python?

Python Question:

I've been trying to get Python 3 to print the mean, sum/len of my dictionary.

I've been looking at methods on stack overflow of how to find the mean of values in a dictionary but every time I try to do it using the keys of values in a dictionary I am riddled with errors. I was able to get the len to work but dividing it doesn't work.

*TL:DR How do I print the mean of values from a Dictionary? on the commented line.

I have cleaned out my code and left an empty line to put in the correct code.

import operator
"Dictionary"
time = {
        'Kristian':19,
        'Alistair':27,
        'Chris':900,
        'Maxi':50, 
        'Jack':15,
        'Milk Man':1
        }
print(time)
print ("-------------------------------")
"Printing the List"
for xyz in time:
    print ("-------------------------------")
    print("\nStudent Name: ", xyz,"\n Time: ", time[xyz],"seconds\n")

"Printing the Results"
def results():
    print ("-------------------------------")
    print("\nThe Fastest Time is: ",(time[min(time, key=time.get)]),"seconds")
    print("\nThe Slowest Time is: ",(time[max(time, key=time.get)]),"seconds")
    print("\nNo. of Competitors: ",len(time))
"//////////Here is where I want to print the mean score\\\\\\\\\\"

results()

"Adding to the Results"
def question():
    person = input("\nPlease enter the student's name: ")
    secs = int(input("Please enter the student's time in seconds: "))
    print("The results you have added are:")
    print("\nStudent Name: ", person,"\n Time: ", secs,"seconds\n")
    sure = input("Are you sure? ").lower()
    if sure in ("no", "n", "nope"):
        question()
    else:
        time.update({person:secs})
        print("Student has been added successfully.")
        results()

"Running the loop"
question()

Upvotes: 1

Views: 3365

Answers (2)

hiro protagonist
hiro protagonist

Reputation: 46901

you mean the values of the dictionary, not the keys, right? then this would work (using statistics.mean):

from statistics import mean
time = {
        'K':19,
        'Al':27,
        'Chris':900,
        'Max':50,
        'Jack':15,
        'Milk Man':1
        }

print(mean(time.values()))  # 168.66666666666666

using dict.values you could also easily get the maximal value a little simpler:

print(max(dct.values()))

maybe time is not the best name for the dictionary; there is a module in the standard library called time. you'd overwrite this module should you import it in the same file.

Upvotes: 1

Moinuddin Quadri
Moinuddin Quadri

Reputation: 48090

dict.values() returns the list of all the values in the Python dictionary. In order to calculate the mean, you may do:

>>> time_values = list(time.values())
#                  ^  Type-cast it to list. In order to make it
#                     compatible with Python 3.x    

>>> mean = sum(time_values)/float(len(time_values))
#                             ^ in order to return the result in float.
#                               division on two `int` returns int value in Python 2    

The value hold by mean will be:

>>> mean
168.66666666666666

Upvotes: 0

Related Questions