On Thu, Jul 09, 2020 at 10:25:46PM +1000, Chris Angelico wrote:

> Getting a random element from a dict (not an arbitrary one but a
> random one) definitely does have a use-case. I've wanted it at times.
> Usually if I'm doing this in Python, I just pay the price and build
> the list, but as proof that it's a logical and useful operation,
> here's Pike's general random function:
> 
> http://pike.lysator.liu.se/generated/manual/modref/ex/predef_3A_3A/random.html
> 
> If given a number, it picks a random number. If given an array, it
> picks a random element. And if given a mapping (dictionary), it
> returns (key,value), without first converting to a flat list.

That's an existance proof that somebody else implemented the function, 
not a use-case. Getting a random key/item pair directly from a dict is a 
mechanism, not an explanation of why you need a random key-item pair.

Analogy:

"Intercal's random function accepts a module as argument and returns the 
value of a random global variable from that module."

(In real life it doesn't, so far as I know, but it should. If not 
Intercal, perhaps Malbolge, or another such escoteric language 
designed to be impractical and frustrating.)

I'll admit that I can't actually think of a reason why one should not 
want a random key/value pair, but that's not the same as being able to 
think of a reason why one *would* want a random key/value pair. Perhaps 
I just lack imagination.

But as you say:

> I don't think the use-case is strong enough, since there are many
> possible variants you might want (imagine using collections.Counter to
> define a weighted average - it'd be handy to say "pick a random
> element, treating this as a bag/multiset"), so it's best to just
> custom write it when you need it.


-- 
Steven
_______________________________________________
Python-ideas mailing list -- python-ideas@python.org
To unsubscribe send an email to python-ideas-le...@python.org
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at 
https://mail.python.org/archives/list/python-ideas@python.org/message/OHDTWNKPANETZ3OUPAO27V24ZI4QDRME/
Code of Conduct: http://python.org/psf/codeofconduct/

Reply via email to