[Tutor] Sorting Dictionary Keys
FT
chester_lab at fltg.net
Wed May 14 02:10:57 CEST 2008
Jim,
OK, use the example below for sorting dictionary keys and placing them in a
list. Note that an error will happen if the format on the print statement
does not correspond to the type of sort.
#THIS SORTS A DICTIONARY BY USING SET THEORY AND DIC ITEMS!
import random
dic = {}
print "Randomizing!"
for i in range(20):
dic[ random.randrange(100)] = random.randrange(100, 1000)
print "Dic:"
j=0
list=[]
for k,i in dic.items():
print "K=%d I=%d" % (k,i)
list.append("K=%d I=%d" % (k,i))
j+=1
j=0
print "Sorted Dic By Set:"
print "Num: Old, Sorted"
for k in sorted(set(dic)):
print "(%d) %s | K=%d I=%d" % (j+1, list[j], k,dic[k])
j+=1
j=0
print "Sorted Dic By Items:"
print "Num: Old, Sorted"
for k,i in sorted(dic.items()):
print "(%d) %s | K=%d I=%d" % (j+1, list[j], k,i)
j+=1
--- On Tue, 5/13/08, James Hartley <jjhartley at gmail.com> wrote:
From: James Hartley <jjhartley at gmail.com>
Subject: [Tutor] sorting dictionary keys?
To: tutor at python.org
Date: Tuesday, May 13, 2008, 11:06 AM
I suspect this is a brain-dead question...
Given the following code, output is as expected:
$ cat test.py
d = { 'a' : 1, 'd' : 2, 'b' : 3, 'c' : 0 }
for i in d.keys():
print "%s\t%s" % (i, d[i])
$ python test.py
a 1
c 0
b 3
d 2
$
But if the keys are sorted, I get an error:
$ cat test1.py
d = { 'a' : 1, 'd' : 2, 'b' : 3, 'c' : 0 }
for i in d.keys().sort():
print "%s\t%s" % (i, d[i])
$ python test1.py
Traceback (most recent call last):
File "test.py", line 3, in <module>
for i in d.keys().sort():
TypeError: 'NoneType' object is not iterable
$
What is the correct manner to iterate through sorted dictionary keys?
Thanks.
Jim
More information about the Tutor
mailing list