Iterating over a dictionary

Alex Martelli alex at magenta.com
Wed Aug 9 07:38:02 EDT 2000


"Thomas Gagne" <tgagne at ix.netcom.com> wrote in message
news:39913C82.4BBF838 at ix.netcom.com...
> If I were iterating over a dictionary, I would expect each "member" would
be
> each association.  It may be because of my smalltalk background but I see
a
> dictionary as just a collection of associations, or at least it should
behave
> that way.

But "association" is not a Python concept.  Perhaps 'pair' (a two-element
tuple) made up of key and value comes closest?  That's the .items()
method.  It also happens to be what C++ gives you when you iterate
over a std::map from its begin() to its end() -- at each step, just a
std::pair of the key and value.


> As it turns out, iterating over a dictionary didn't work for my
> purpose--creating a packed representation of a C structure, because the
> associations woule re-order themselves (probably by hash value) so when I
went
> to assemble the structure the variables were out of order.

Yes, iteration over a mapping (be it by .items, .values or .keys) is
in "random", arbitrary order.  This is crucial to enable whatever
internal representation is handiest (and a dict uses a hash table),
differently from C++'s std::map where (key,value) pairs are
specified to be returned in key-sorted order (which practically
imposes some sort of tree-structure for the internal representation).
But even in that case the sequence would be determined by the
data and probably not match your requirements.


> I ended up using a tuple (neat stuff - I'm getting to like Python).  What
I

Yes, if you need a specific sequence order then tuples or lists are most
likely better than any mapping.  After all that's what distinguishes a
sequence as an abstract type from, say, a bag -- order of elements
is significant.

> really liked was:
>
> for x,y in myTyple:
>     do something with x and y
>
> Now THAT'S slick.

Auto-unpacking of tuples on assignment (binding)?  Yep, quite handy indeed!


Alex






More information about the Python-list mailing list