jAC
jAC

Reputation: 3445

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

Upvotes: 0

Views: 335

Answers (2)

Emil
Emil

Reputation: 73

np.random.choice([k for k in dict.keys() if dict[key]==min(dict.values())])

Upvotes: 0

pakpe
pakpe

Reputation: 5489

Here is one solution:

import random
dic = {'a': 1, 'b': 2, 'c': 5, 'd':1, 'e': 5, 'f': 1}

a = random.choice([k for k,v in dic.items() if v == min(dic.values())])

Upvotes: 1

Related Questions