On Thu, Jul 9, 2020 at 9:16 PM Steven D'Aprano <st...@pearwood.info> wrote:
> Unless I have missed any others, we've only seen three use-cases:
>
> (a) The original post wanted a full sequence API for dictionaries, with
> the ability to insert keys at a specific index, not just get the N-th
> key. Not going to happen.
>
> (b) You've suggested "get any item", but that's probably better written
> as `next(mydict.items)`.
>
> (c) And `random.choice(mydict.items())` which seems to be lacking any
> *concrete* use-case -- under what circumstances would we want this and
> care about it's performance *enough* to add this to builtin dict views?
>

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.

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. But if it's needed, it would want to
be on the dictionary itself, not on the views, IMO.

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

Reply via email to