[Python-ideas] Iteritems() function?

Mathias Panzenböck grosser.meister.morti at gmx.net
Wed Jun 8 17:41:28 CEST 2011


On 06/08/2011 01:54 PM, Oleg Broytman wrote:
> On Wed, Jun 08, 2011 at 01:01:08PM +0200, Jan Kaliszewski wrote:
>> Quite typical: iterate and do something with some_items -- a collection
>> of 2-element items.
>>
>>      for first, second in some_items:
>>          ...
>>
>> But for dicts it must use another form:
>>
>>      for first, second in some_items.items():
>>          ...
>>
>> We must know it'll be a mapping, and even then quite usual bug is to
>> forget to add that `items()'.
>
>     You don't need a special buitin for that. Just call .items():
>
> if hasattr(some_items, 'items'):
>      some_items = some_items.items()
> for first, second in some_items:
>      ...
>
> Oleg.

So basically it would be:

def items(sequence):
	if hasattr(sequence, 'items'):
		return sequence.items()
	else:
		return sequence

I don't think that is enough complexity to justify an inclusion in builtins or itertools. Anyway, I 
would have expected such a function to do this (so it's not even obvious):

def items(sequence):
	if hasattr(sequence, 'items'):
		return sequence.items()
	else:
		return enumerate(sequence)


	-panzi



More information about the Python-ideas mailing list