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?
To get a random value from a dictionary in Python, you can use the random module choice() function, list() function and dictionary values() function. If you want to get a random key from a dictionary, you can use the dictionary keys() function instead.
Python dictionary | values() values() is an inbuilt method in Python programming language that returns a view object. The view object contains the values of the dictionary, as a list. If you use the type() method on the return value, you get “dict_values object”. It must be cast to obtain the actual list.
Using random. randrange() to select random value from a list. random. randrange() method is used to generate a random number in a given range, we can specify the range to be 0 to the length of the list, and get the index, and then the corresponding value.
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.
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'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With