[Tutor] outputting dictionary key/value pairs
Terry Carroll
carroll at tjc.com
Wed Aug 6 17:57:59 EDT 2003
On Fri, 1 Aug 2003, Terence Lo wrote:
> supoose i create a dictionary of the form:
>
> dict = {"d1": "a", "d2": "b", "d3": "c"}
>
> why is it that when i loop through the dictionary,
>
> eg.
>
> 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.
Yep. that's the way dictionaries work.
> is there a quick way to loop through the dict and output the contents in
> order? namely d1 .. d2.. d3 ?
Try this:
keylist = dict.keys()
keylist.sort()
for k in keylist:
print k, dict[k]
--
Terry Carroll | "I say to you that the VCR is to the American
Santa Clara, CA | film producer and the American public as the
carroll at tjc.com | Boston strangler is to the woman home alone."
| Jack Valenti, MPAA President
Modell delendus est | Testimony before Congress, 1982
More information about the Tutor
mailing list