On Fri, Oct 08, 2021 at 01:42:35PM -0700, Christopher Barker wrote:

> It really ius frustrating how often we repeat entire conversations on this
> list :-(

That's because y'all don't just admit I'm right the first time *wink*


> But last time, one of the use cases was "get a random item from a dict",
> and there really is not a terribly easy (and efficient) way to do that now.

Dicts are hash tables, not sequences. I think that the most efficient 
way to get a random item from a dict is to convert it to a list first, 
and then get the random item from the list. Not every data structure is 
well-suited to random access by position.

But what's your use-case for getting a random item from a dict?

Apart from a programming exercise and teaching moment, why would you 
want to get a random key and value from a dict? In 25-ish years of using 
Python, I think that the number of times I've needed to do that is zero. 
A random item from a list, dozens of times. But from a dict, never.

(I'm not even convinced that dict.popitem is useful either. But maybe 
that's just me, and others use it ten times a day.)

I'm not saying that there is no good reason to do so, but it is hardly a 
common task.

In any case, if you want a *random* item, using `first()` and getting 
the first item every time is hardly random. It's not even really a good 
match for an *arbitrary* item.

"In the case of a tie, the winner is the candidate sitting closest to 
the door."

We introduced random.choice() back in Python 2.1. Nobody noticed until 
3.4 that it didn't work on dicts, or at least they didn't care enough to 
raise a feature request to support dicts directly.

https://bugs.python.org/issue33098

For many years in Python 2, random.choice() accidentally appeared to 
work with dicts if they were keyed with integers 0...len(dict), but 
returned values rather than keys. And nobody seems to have noticed. At 
least I can't find any reports in the bug tracker.

So the evidence from the bug tracker suggests that getting a random key, 
value or item from a dict is more common as a programming exercise than 
a genuine thing that people need to do to solve real problems.


-- 
Steve
_______________________________________________
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/NDPM5LLUKZH34RU6S5WUG45ULTMWZ6OH/
Code of Conduct: http://python.org/psf/codeofconduct/

Reply via email to