[Tutor] outputting dictionary key/value pairs

Bob Gailer bgailer at alum.rpi.edu
Thu Aug 7 12:37:46 EDT 2003


At 12:18 PM 8/1/2003 -0400, Terence Lo wrote:
>supoose i create a dictionary dict = {"d1": "a", "d2": "b", "d3": "c"}
>when i loop through the dictionary,
>for k,v in dict.items():
>         print k,v
>the dictionary items aren't output in the order they appear in the
>dictionary.  they seem to be returned in an arbitrary order.

Dictionaries are stored using some kind of binary tree that manages the 
hashed values of its keys. There is no attempt at maintaining any order.

>is there a quick way to loop through the dict and output the contents in
>order?  namely  d1 .. d2.. d3 ?

keys = dict.keys()
keys.sort()
for k in keys:
     print k, dict[k]

Bob Gailer
bgailer at alum.rpi.edu
303 442 2625
-------------- next part --------------

---
Outgoing mail is certified Virus Free.
Checked by AVG anti-virus system (http://www.grisoft.com).
Version: 6.0.506 / Virus Database: 303 - Release Date: 8/1/2003


More information about the Tutor mailing list