jeudi 7 novembre 2019

How to break a tie randomly from the highest values of a dictionary in Python?

I want to return the key that has the highest value in a dictionary, and if there is a tie, to choose one of them randomly. I know how to get the max value, but can't figure out how to break a tie.

max(result, key = result.get) 

This gets me the max value, but if the dictionary has a tie, then it just gives me the first one it comes across

Given the dictionary {'banana': 3, 'apple': 2, 'cherry': 1, 'orange': 3}

Output must either give banana or orange, but at random.




Aucun commentaire:

Enregistrer un commentaire