On Sat, Jul 11, 2020 at 3:45 PM Christopher Barker <pythonchb@gmail.com> wrote:
On Fri, Jul 10, 2020 at 12:45 PM David Mertz <mertz@gnosis.cx> wrote:
The strongest argument I've seen is: `list(d.items())` adds six characters.
1) Matching our mental model / usability: if I want the nth item (or a random item) from a dict, I want to ask for that -- I don't want to make a list, just to index it and throw it away. the list(d.items()) idiom is the right one if I actually need a list -- it's a bit awkward to have to make a list, just to throw it away. 2) Performance: making an entire list just to get one item out is a potentially expensive operation. Again, for the limited use cases, probably not a big deal, I'm having a really hard time imagining a application where that would be a bottleneck, but it is *a* reason, if not a compelling one.
For the single case of wanting JUST ONE random key/val pair from a dictionary EVER, I agree random.choice(d.items()) looks a little better. I even agree that it's something that probably seems obvious to try the first time. However, once you want to get multiple items, the amortized costs starts to matter. I think that latter situation is likely to be VASTLY more common in real code... but I'm just saying that without evidence. Still, this is such a narrow situation, I just don't see it as justifying a language change (the "get an item, only once" case). Code that I can easily imagine writing (although I'm not sure I actually have): items = dict.items() while True: k, v = random.choice(items) if satisfies_need(k, v): do_stuff(k, v) break The hypothetical view-sequence would be an attractive nuisance that would hurt performance in all such similar code. -- The dead increasingly dominate and strangle both the living and the not-yet born. Vampiric capital and undead corporate persons abuse the lives and control the thoughts of homo faber. Ideas, once born, become abortifacients against new conceptions.