0

I am a beginner in Python. I have written a code in which the name of the contestants and their scores will be stored in a dictionary. Let me call the dictionary as results. However I have left it empty while writing the code. The keys and values are going to be added to the dictionary when the program is being run.

results={}     
name=raw_input()
    #some lines of code to get the score#
results[name]=score
    #code#
name=raw_input()
    #some lines of code to get the score#
results[name]=score

After the execution of the program, let us say results == {"john":22, "max":20}

I want to compare the scores of John and Max, and declare the person with highest score as a winner. But I wont be knowing the names of the contestants at the beginning of the program. So how can I compare the scores, and declare one of them as the winner.

martineau
  • 119,623
  • 25
  • 170
  • 301

3 Answers3

2

You can just do this, to get the winner:

max(results, key=results.get)
Seba
  • 552
  • 3
  • 10
1

Here's a working example to achieve what you want, which is basically getting the maximum item from a dictionary. In the example you'll also see other gems like generating deterministic random values instead inserting them manually and getting the min value, here you go:

import random
import operator

results = {}

names = ["Abigail", "Douglas", "Henry", "John", "Quincy", "Samuel",
         "Scott", "Jane", "Joseph", "Theodor", "Alfred", "Aeschylus"]

random.seed(1)
for name in names:
    results[name] = 18 + int(random.random() * 60)

sorted_results = sorted(results.items(), key=operator.itemgetter(1))

print "This is your input", results
print "This is your sorted input", sorted_results
print "The oldest guy is", sorted_results[-1]
print "The youngest guy is", sorted_results[0]
BPL
  • 9,632
  • 9
  • 59
  • 117
0

you can do:

import operator
stats = {'john':22, 'max':20}
maxKey = max(stats.items(), key=operator.itemgetter(1))[0]
print(maxKey,stats[maxKey])

you can also get the max tuple as a whole this way:

maxTuple = max(stats.items(), key=lambda x: x[1])

Hope it helps!

Soheil__K
  • 642
  • 1
  • 8
  • 17