james
james

Reputation: 19

how to print 2 or more random key from a dictionary in python

build_dic = {}
with open (filedictionary, 'r') as df:
    for kv in [d.strip().split(':') for d in df]:
        build_dic[kv[0]] = kv[1]

for key in build_dic:
    key = random.sample(build_dic, n)
    print key

and when i run it, it comes with

['to study', 'to talk', 'to make']
['to make', 'to run', 'to practice']
['to run', 'to talk', 'to take']
['to arrive', 'to practice', 'to suck']
['to run', 'to search', 'to practice']
['to arrive', 'to suck', 'to talk']
['to search', 'to like', 'to take']
['to take', 'to play', 'to study']
['to study', 'to take', 'to practice']
['to suck', 'to search', 'to run']
['to play', 'to suck', 'to make']
['to suck', 'to talk', 'to search']

what shall i do? I just want to 3 random keys from my dic.

Upvotes: 1

Views: 38

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1124090

Don't use a loop. You are looping over all the keys in the dictionary, and picking a new sample each iteration.

Just use random.sample() once:

n = 3
random_keys = random.sample(build_dic, n)
print random_keys

You can loop over the result of random.sample() of course.

Upvotes: 1

Related Questions