Iterating over a dictionary

Alex Martelli alex at magenta.com
Tue Aug 8 12:21:12 EDT 2000


"Thomas Gagne" <tgagne at ix.netcom.com> wrote in message
news:398FF8FE.34918FE2 at ix.netcom.com...
> Given a dictionary, is there a method to do something inside a code block
for
> each member of the dictionary?  Would that same member work for other
kinds of
> collections as well?

The "kinds of collections" are two: sequences and mappings.  A dictionary is
the
typical example of a mapping.

A mapping implements methods .items(), returning a sequence (list, actually)
of (key,value) pairs; .keys(), returning a sequence of keys; .values(),
returning
a sequence of values.  Not sure which one you mean by "each member" --
is it each key, each value, or each (key,value) pair?

Anyway, a sequence does not (necessarily) implement any of these methods;
it IS the sequence of its items (would you call those 'members')?  So, you
cannot call, e.g., .items() on it -- but you can iterate on it directly.

So, depending on what you want, it could be something like, e.g.:

def dosomething(acollection, acodeblock):
    try:
        map(acodeblock,acollection.values())
    except AttributeError:
        map(acodeblock,acollection)

This will call acodeblock(x) for each x in the acollection sequence,
but if object acollection has a method called values() then it will
instead do it for each x in the sequence returned by .values() [and
this applies to dictionaries in particular].

Is this what you mean...?


Alex






More information about the Python-list mailing list