select random entry from dictionary

Skip Montanaro skip at pobox.com
Tue Mar 8 11:20:32 EST 2005


    >> 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))

    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



More information about the Python-list mailing list