Alex Waygood writes:
Whereas obviously,
The temptation to insist "see, YAGNI!" at this point I shall resist.
a much better way (especially if it's a very large dictionary) is to do:
first_key = next(iter(mydict))
[Inada Naoki]
I think we can add `itertools.first()` for this idiom, and `itertools.last()` for `next(iter(reversed(x)))` idiom.
I was +0 sympathetic to that until you posted this obvious extension of the idea:
I like this idea, a lot. Another possibility I've been wondering about was whether several methods should be added to the dict interface: dict.first_key = lambda self: next(iter(self)) dict.first_val = lambda self: next(iter(self.values())) dict.first_item = lambda self: next(iter(self.items())) dict.last_key = lambda self: next(reversed(self)) dict.last_val = lambda self: next(reversed(self.values())) dict.last_item = lambda self: next(reversed(self.items()))
That's an awful lot of new methods to take advantage of what for many applications of dict (in fact, *all* of my applications ever[1]) is an irrelevant ordering. And anyone who wants it can do it themselves: def first_key(dct): return next(iter(dct)) def first_val(dct): return next(iter(dct.values())) def first_item(dct): return next(iter(dct.items())) def last_key(dct): return next(reversed(iter(dct))) def last_val(dct): return next(reversed(iter(dct.values()))) def last_item(dct): return next(reversed(iter(dct.items()))) These defs do something undefined on unordered mappings (ie, not based on dict), and may be dangerous in that sense. OTOH, I suspect the methods will do the wrong thing with many ordered mappings based on dict that support orders other than insertion order.
But I think I like a lot more the idea of adding general ways of doing these things to itertools.
If you want to convince others, you really need to be more specific about the requirements that lead you to this conclusion. In the current implementation, positional indexing is time-expensive, much more so than keeping an auxiliary list and using dct[lst[ndx]]. It could also allow timing attacks if used in security-sensitive code. And I wonder if any code is being written obscurely to ensure that keys get added to dicts in the "right" order, instead of keeping an explict, efficient, and reorderable auxiliary list of keys? Footnotes: [1] It's true that some code I import is probably improved because the developers don't waste time tracking down test failures in dict- based data structures. :-)