how about this
>>> d = { 'a' : 1, 'd' : 2, 'b' : 3, 'c' : 0 }
>>> for i in sorted(set(d)):
... print "%s\t%s" % (i, d[i])
...
a 1
b 3
c 0
d 2
James Hartley wrote:
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
_______________________________________________
Tutor maillist - [email protected]
http://mail.python.org/mailman/listinfo/tutor
_______________________________________________
Tutor maillist - [email protected]
http://mail.python.org/mailman/listinfo/tutor