how can i randomly choose keys in dictionary

N

neutrinman

Hi,there. How can I choose a key in dictionary randomly?

Say, random.choice() in lists,

or in lists:
lists = [1,2,3,4]
position = random.range(len(lists))
word = lists[position]
 
T

Thomas Guettler

Am Thu, 17 Feb 2005 18:13:46 -0800 schrieb neutrinman:
Hi,there. How can I choose a key in dictionary randomly?

Say, random.choice() in lists,

or in lists:
lists = [1,2,3,4]
position = random.range(len(lists))
word = lists[position]

Hi, try this:

import random

mydict={1: "one", 2: "two"}
print mydict[random.choice(mydict.keys())]
 
J

John Lenton

Am Thu, 17 Feb 2005 18:13:46 -0800 schrieb neutrinman:
Hi,there. How can I choose a key in dictionary randomly?

Say, random.choice() in lists,

or in lists:
lists = [1,2,3,4]
position = random.range(len(lists))
word = lists[position]

Hi, try this:

import random

mydict={1: "one", 2: "two"}
print mydict[random.choice(mydict.keys())]

if you're going to do that, why don't you do

print random.choice(mydict.values())

?

--
John Lenton ([email protected]) -- Random fortune:
Quien da parte de sus cohechos, de sus tuertos hace derechos.

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.0 (GNU/Linux)

iD8DBQFCFf9lgPqu395ykGsRAjkKAKCQfjMQhBDzea1mS3AvTYDp+wYYOQCdEBI4
M2hvb/3LFnOElltdctHgv6Y=
=6ffX
-----END PGP SIGNATURE-----
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top