Search code examples
pythonrandommax

Using max() to find highest in a list, and if they tie, choose only one


I'm making a voting software and having some problems. Here is a sample:

import random

One = "James"
Two = "Tabitha"
Three = "Emory"

running = {One: 0, Two: 0, Three: 0}

#Enter voting code here

winner = max(running)

I want to make it so if two candidates tie for the win, it will randomly select one of them as the winner. Is there any way to do this?


Solution

  • You could find the max number of votes, and then select the key(s) from the dictionary that have that value:

    max_votes = max(running.values())
    winners = [candidate for candidate, votes in running.items() if votes == max_votes]
    winner = random.choice(winners)