lundi 22 février 2021

Python get random value when using min() when there is more than one match

I have the following code:

dict = {'a': 1, 'b': 2, 'c': 5, 'd':1, 'e': 5, 'f': 1}
get_min = min(dict, key=dict.get)

As you can see here there is actually three min() matches "a", "d" and "f" with the value of 1.

This will return "a" 100% of the time as that is what min() is designed to do from what I am reading. However, I have a need where I would like to randomly get back "a", "d" or "f" instead of just "a".

Is there a way I can do this using min() or some other way (maybe lambda, I am not very good at it)? I thought this would be pretty simple but it turns out it is not :P. I can get this working with some for loops and creating lists but I was looking for the shortest way possible.

Your thoughts would be appreciated!

Thanks,

jAC




Aucun commentaire:

Enregistrer un commentaire