how can i randomly choose keys in dictionary

Discussion in 'Python' started by neutrinman, Feb 18, 2005.

  1. neutrinman

    neutrinman Guest

    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]
    neutrinman, Feb 18, 2005
    1. Advertisements

  2. Am Thu, 17 Feb 2005 18:13:46 -0800 schrieb neutrinman:
    Hi, try this:

    import random

    mydict={1: "one", 2: "two"}
    print mydict[random.choice(mydict.keys())]
    Thomas Guettler, Feb 18, 2005
    1. Advertisements

  3. neutrinman

    John Lenton Guest

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

    print random.choice(mydict.values())


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

    Version: GnuPG v1.4.0 (GNU/Linux)

    -----END PGP SIGNATURE-----
    John Lenton, Feb 18, 2005
    1. Advertisements

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 (here). After that, you can post your question and our members will help you out.