select random entry from dictionary

Discussion in 'Python' started by Tor Erik Sønvisen, Mar 8, 2005.

  1. Hi

    How can I select a random entry from a dictionary, regardless of its
    key-values?

    regards tores
     
    Tor Erik Sønvisen, Mar 8, 2005
    #1
    1. Advertisements

  2. Tor Erik Sønvisen

    gaudetteje Guest

    From the Python 2.4 quickreference:

    d.popitem() Removes and returns an arbitrary (key, value) pair from
    d

    If this isn't random enough, then you can generate a random number in
    range(len(d))
     
    gaudetteje, Mar 8, 2005
    #2
    1. Advertisements

  3. Tor Erik Sønvisen

    chengdu Guest

    import random

    print d[d.keys()[int(random.random()*len(d.keys()))]]

    HTH

    -c
     
    chengdu, Mar 8, 2005
    #3
  4. Tor Erik Sønvisen

    Peter Hansen Guest

    Although this idea may suit the OP, "arbitrary" is
    most definitely not "random". Given the same
    dictionary on two separate occasions, this approach
    results in precisely the same sequence of items
    being returned.

    -Peter
     
    Peter Hansen, Mar 8, 2005
    #4
  5. d.popitem() Removes and returns an arbitrary (key, value) pair from d

    Peter> Although this idea may suit the OP, "arbitrary" is most
    Peter> definitely not "random".

    Correct. The library reference is pretty clear about this too:

    Keys and values are listed in an arbitrary order which is non-random,
    varies across Python implementations, and depends on the dictionary's
    history of insertions and deletions.

    (This is from note 3 of http://docs.python.org/lib/typesmapping.html, which
    is referenced six times from the operations table on that page.)

    It's tempting to think it's random because you see the order change in
    seemingly unpredictable ways, but it's definitely not.

    Skip
     
    Skip Montanaro, Mar 8, 2005
    #5
  6. Tor Erik Sønvisen

    gaudetteje Guest

    Peter,

    Agreed... which is why I said the 'random' module should be imported if
    more randomness is required.

    I only mentioned d.popitem() first in case Tores' application didn't
    need a psuedo-random item and instead he was looking to pull any value
    without randomness.
     
    gaudetteje, Mar 8, 2005
    #6
    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.