[Tutor] iterating over sorted dictionary keys (this right?)
kevin parks
kp8 at mac.com
Sun Mar 28 03:28:30 EST 2004
hi.
I'd like to check and see if i am on the right path and that i am
understanding things. I have a hard time getting my head around
dictionaries as Python is the first language that i have used that has
them and as i result i almost always use lists... Still it is clear to
me that dictionaries are helpful and sometimes have advantages so i am
forcing myself to learn and use them.
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:
for key, value in page02.items():
as i have now sorted my keys (is that right, or am i misunderstanding
how items() works?)
In any case i am getting (i think) the right thing by changing :
print len(page02)
line_num = 1
for key, value in page02.items():
print line_num,"\tKey = %s" %str(key), "\tValue = %s"
%str(value)
line_num = line_num + 1
# 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
here is the whole ball of wax:
#!/usr/bin/env python
def test():
page02 = {
(1,0) : [8, 3, 5, 4],
(7,0) : [4, 3, 2, 2],
(14,0) : [8, 3, 5, 4],
(18,0) : [10, 2, 8, 7],
(20,0) : [10, 0, 5, 7],
(22,0) : [10, 2, 8, 7],
(24,0) : [7, 9, 3, 8],
# (25,0) : [5],
# (27,0) : [0],
(28,0) : [10, 0, 5, 7],
(29,0) : [10, 11],
(30,0) : [8, 3, 5, 4],
(32,0) : [5, 0, 10, 7],
(34,0) : [8, 3, 7, 9],
(36,0) : [5, 4, 3, 1],
(36,1) : [5, 4, 3, 1, 7],
(37,0) : [0, 8, 2, 4, 9, 10, 1],
(37,1) : [0, 8, 2, 4, 9, 10, 1, 6],
(39,0) : [8, 10, 1, 9],
(39,1) : [8, 10, 1, 9, 7],
(41,0) : [2, 0, 3, 1],
(41,1) : [2, 0, 3, 1, 6] }
print len(page02)
line_num = 1
for key, value in page02.items():
print line_num,"\tKey = %s" %str(key), "\tValue = %s"
%str(value)
line_num = line_num + 1
# -- ----
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
# -- -+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-
if __name__ == "__main__":
test()
More information about the Tutor
mailing list