[Tutor] Dictionary

Magnus Lycka magnus@thinkware.se
Sat Nov 23 12:49:01 2002


At 17:00 2002-11-23 +0100, lumbricus@gmx.net wrote:
> >>> [ d[key] for key in d.keys() ]
>[2, 4, 6]

Long form on "d.values()"?

> >>> # It's sorted :-o
> >>> [ (key, d[key]) for key in d.keys() ]
>[(1, 2), (3, 4), (5, 6)]

Long form of "d.items()"?

But see below:

 >>> {1:1, 22:2, 333:3, 4444:4, 55555:5}.keys()
[1, 55555, 4444, 333, 22]

>Is it incident or a feature? Can we rely on that
>behaviour?

As seen above, you can't rely on that. See library reference
2.2.7, note (3). "Keys and values are listed in random order."
I think it should really say "arbitrary" order or something
like that, but the intention with that text must be to warn
you from expecting to get a sorted list, even if that is what
you get now for SOME key values. Think about how hashing
algorithms work, and I think it will be clear. (I just realized
that hashing algorithms might not be obvious to all list
members, but my wife is calling. Got to eat... Use google. :)

The only thing you can count on is that if you don't
change your dict, the order in .keys(), .values() and
.items() will be coordinated and repetetive.


-- 
Magnus Lycka, Thinkware AB
Alvans vag 99, SE-907 50 UMEA, SWEDEN
phone: int+46 70 582 80 65, fax: int+46 70 612 80 65
http://www.thinkware.se/  mailto:magnus@thinkware.se