JayGatsby
JayGatsby

Reputation: 1621

Selecting random values from dictionary

Let's say I have this dictionary:

dict = {'a': 100, 'b': 5, 'c': 150, 'd': 60};

I get the key which has greatest value with this code:

most_similar = max(dic.iteritems(), key=operator.itemgetter(1))[0]

it returns 'c'

But I want to select a random key from top 3 greatest values. According to this dictionary top 3 are:

c
a
d

It should randomly select a key from them. How can I do that?

Upvotes: 8

Views: 1186

Answers (3)

TigerhawkT3
TigerhawkT3

Reputation: 49318

Sort the dictionary by descending value, get the first three objects from the resulting list, then use random.choice:

>>> import random
>>> d = {'a': 100, 'b': 5, 'c': 150, 'd': 60}
>>> random.choice(sorted(d, reverse=True, key=d.get)[:3])
'c'

And don't call it dict or you'll mask the built-in.

Upvotes: 4

thefourtheye
thefourtheye

Reputation: 239463

If you want to find the top 3 keys and then get one of the keys randomly, then I would recommend using random.choice and collections.Counter, like this

>>> d = {'a': 100, 'b': 5, 'c': 150, 'd': 60}
>>> from collections import Counter
>>> from random import choice
>>> choice(Counter(d).most_common(3))[0]
'c'

Counter(d).most_common(3) will get the top three values from the dictionary based on the values of the dictionary object passed to it and then we randomly pick one of the returned values and return only the key from it.

Upvotes: 13

timgeb
timgeb

Reputation: 78690

Get the keys with the three largest values.

>>> import heapq
>>> d = {'a': 100, 'b': 5, 'c': 150, 'd': 60}
>>> largest = heapq.nlargest(3, d, key=d.__getitem__)
>>> largest
['c', 'a', 'd']

Then select one of them randomly:

>>> import random
>>> random.choice(largest)
'c'

Upvotes: 7

Related Questions