[Python-ideas] Iteritems() function?

Steven D'Aprano steve at pearwood.info
Thu Jun 9 02:38:23 CEST 2011


Masklinn wrote:
> On 2011-06-08, at 19:57 , Matt Billenstein wrote:
>> On Wed, Jun 08, 2011 at 01:25:42PM +0200, Masklinn wrote:
>>> You could just convert everything to a dict:
>>>
>>>    for first, second in dict(some_items).iteritems():
>>>        # etc?
>> That option won't necessarily preserve the order of the original sequence where
>> perhaps it matters…
>>
> That is what collections.OrderedDict is for.

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




More information about the Python-ideas mailing list