Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 946
JayGatsby Avatar asked Jan 10 '16 15:01

JayGatsby


People also ask

How do you pick a random value from a dictionary?

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.

How do you only find values in a dictionary?

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.

How do you pick a random value from a list in Python?

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.


2 Answers

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.

like image 185
thefourtheye Avatar answered Nov 15 '22 20:11

thefourtheye


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'
like image 38
timgeb Avatar answered Nov 15 '22 21:11

timgeb