[Tutor] iterating over sorted dictionary keys (this right?)
Karl Pflästerer
sigurd at 12move.de
Sun Mar 28 14:06:02 EST 2004
On 28 Mar 2004, kevin parks <- kp8 at mac.com wrote:
> I need to iterate over a dictionary, but since my key is a time value,
> order matters. So i am trying to iterate over a sorted copy of my
> keys. I am guessing that i can no longer use the items method:
Right.
> for key, value in page02.items():
> as i have now sorted my keys (is that right, or am i misunderstanding
> how items() works?)
No you are right.
> In any case i am getting (i think) the right thing by changing :
[...]
> # to
> mykeys = page02.keys() # first make a copy of the keys
> print '-+' * 26
> print mykeys # print it and take a look
> print '-+' * 26
> mykeys.sort() # now sort that copy in place
> print mykeys
> line_num = 1 # let's count our lines
> print '-+' * 26
> # iterate over the sorted keys
> for key in mykeys:
> print line_num,"\tKey = %s" %str(key), "\tValue = %s"
> %str(page02[key])
> line_num = line_num + 1
That's absolutely right. (the data structure looks now much cleaner).
Karl
--
Please do *not* send copies of replies to me.
I read the list
More information about the Tutor
mailing list