[Python-ideas] Iteritems() function?

Jan Kaliszewski zuo at chopin.edu.pl
Wed Jun 8 13:01:08 CEST 2011


Case
====

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()'.

But sometimes it may be a dict {first: second, ...} OR a seq [(first,
second), ...] and in fact we are not interested in it -- we simply want
to iterate over its items... But we are forced to do type/interface
check, e.g.:

    if isinstance(coll, collections.Mapping):
        for first, second in some_items.items(): ...
    else:
        for first, second in some_items: ...

Idea
====

A new function:
    builtins.iteritems()
or
    builtins.iterpairs()
or
    itertools.items()
or
    itertools.pairs()
(don't know what name would be the best)

-- equivalent to:

    def <one of the above names>(coll):
        iterable = (coll.items()
                    if isinstance(coll, collections.Mapping)
                    else coll)
        return iter(iterable)

or maybe something like:

    def <one of the above names>(coll):
        try:
            iterable = coll.items()
        except AttributeError:
            iterable = coll
        return iter(iterable)

Usage
=====

Then, in our example case, we'd do simply:

    for first, second in iteritems(some_items):
        ...

And we don't need to think about some_items type, whether it's a mapping
or 2-tuple sequence. All we need to know is that it's a collection of
2-element items.

Regards,
*j




More information about the Python-ideas mailing list