select random entry from dictionary

  • Thread starter Tor Erik Sønvisen
  • Start date
T

Tor Erik Sønvisen

Hi

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

regards tores
 
G

gaudetteje

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

Peter Hansen

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

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
 
S

Skip Montanaro

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
 
G

gaudetteje

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.
 

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,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top