Re: [Python-ideas] Iteritems() function?

On Wed, Jun 08, 2011 at 01:25:42PM +0200, Masklinn wrote:
That option won't necessarily preserve the order of the original sequence where perhaps it matters... m -- Matt Billenstein matt@vazor.com http://www.vazor.com/

Masklinn wrote:
But calling *dict* on the items (as shown above), not OrderedDict, doesn't preserve the order. And frankly, I think it's silly to take an arbitrarily big iterable of ordered items, convert it to a dict (ordered or not), only to immediately extract an ordered iterable of items again: OrderedDict(some_items).items() You already have some_items in the right format for iteration, why iterate over it twice instead of once? Better to use a simple helper function: def coerce_to_items(obj): if has_attr(obj, 'items'): return obj.items() return obj which accepts either a mapping (dict or OrderedDict) or an iterable of items, and returns an iterable of items. (I use items() rather than iteritems() because any proposed new functionality must be aimed at Python 3, not 2.) That's simple enough to use in-line, if you use small variable names: for a,b in (pairs.items() if hasattr(pairs, 'items') else pairs): ... but I think the utility function is better. I don't think it needs to be a built-in. -- Steven

Masklinn wrote:
But calling *dict* on the items (as shown above), not OrderedDict, doesn't preserve the order. And frankly, I think it's silly to take an arbitrarily big iterable of ordered items, convert it to a dict (ordered or not), only to immediately extract an ordered iterable of items again: OrderedDict(some_items).items() You already have some_items in the right format for iteration, why iterate over it twice instead of once? Better to use a simple helper function: def coerce_to_items(obj): if has_attr(obj, 'items'): return obj.items() return obj which accepts either a mapping (dict or OrderedDict) or an iterable of items, and returns an iterable of items. (I use items() rather than iteritems() because any proposed new functionality must be aimed at Python 3, not 2.) That's simple enough to use in-line, if you use small variable names: for a,b in (pairs.items() if hasattr(pairs, 'items') else pairs): ... but I think the utility function is better. I don't think it needs to be a built-in. -- Steven
participants (3)
-
Masklinn
-
Matt Billenstein
-
Steven D'Aprano