Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pull random keys from dictionary in Python that are not equal to one another

So I'm trying to setup a multiple choice quiz via Python. I'm fairly new to Python, so my apologies up front if there is a simpler way to do this. However, I'm trying to really understand some basics before moving forward to newer techniques.

I have a dictionary. In this dictionary, I want to grab 3 random keys. I also want to make sure that these three keys are not equal (in other words, random from one another). Here is the code I have wrote so far:

import random

word_drills = {'class': 'Tell Python to make a new kind of thing.',
               'object': 'Two meanings: the most basic kind of thing, and any instance of some thing.',
               'instance': 'What you get when you tell Python to create a class.',
               'def': 'How you define a function inside a class.',
               'self': 'Inside the functions in a class, self is a variable for the instance/object being accessed.',
               'inheritance': 'The concept that one class can inherit traits from another class, much like you and your parents.',
               'composition': 'The concept that a class can be composed of other classes as parts, much like how a car has wheels.',
               'attribute': 'A property classes have that are from composition and are usually variables.',
               'is-a': 'A phrase to say that something inherits from another, as in a Salmon *** Fish',
               'has-a': 'A phrase to say that something is composed of other things or has a trait, as in a Salmon *** mouth.'}

key1 = ' '
key2 = ' '
key3 = ' '             

def nodupchoice():
    while key1 == key2 == key3: 
        key1 = random.choice(word_drills.keys())
        key2 = random.choice(word_drills.keys())
        key3 = random.choice(word_drills.keys())


nodupchoice()

print "Key #1: %s, Key #2: %s, Key #3: %s" % (key1, key2, key3)

I'm fairly sure the issue is with my while loop. I wanted to create a function that will keep running until all three keys are different from one another. Finally, it would print the result. Any ideas? Thanks in advance.

like image 992
kiddsupreme Avatar asked Aug 18 '12 21:08

kiddsupreme


2 Answers

You can use random.sample:

>>> random.sample(word_drills, 3)
['has-a', 'attribute', 'instance']

and you don't need .keys(), iteration over a dictionary is over the keys.

Note that random.sample will return three unique values from the list you supply (i.e. it will never return 'has-a' twice):

>>> all(len(set(random.sample(word_drills, 3))) == 3 for i in range(10**5))
True
like image 89
DSM Avatar answered Oct 11 '22 03:10

DSM


Use random.sample

>>> import random
>>> random.sample([1,2,3,4,5,6], 3)
[4, 5, 2]
like image 3
applicative_functor Avatar answered Oct 11 '22 01:10

applicative_functor