dimanche 10 janvier 2016

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?




Aucun commentaire:

Enregistrer un commentaire