[Tutor] outputting dictionary key/value pairs

Zak Arntson zak at harlekin-maus.com
Wed Aug 6 18:21:36 EDT 2003


>> 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

Here's an alternative approach, if you'd like to keep a sorted list of
keys and values around. This approach is, though, of dubious use.

###
>>> d = {'d1':'a', 'd2':'b', 'd3':'c'}
>>> d_list = [(k, v) for k, v in d.items()]
>>> d_list.sort()

>>> print d_list
[('d1', 'a'), ('d2', 'b'), ('d3', 'c')]

>>> for d_tuple in d_list:
        print d_tuple[0], d_tuple[1]

d1 a
d2 b
d3 c
###

Also, I'd like to point out that you shouldn't be using 'dict' as a
variable name, since it's already defined in Python

###
>>> dict
<type 'dict'>
###

---
Zak Arntson
www.harlekin-maus.com - Games - Lots of 'em



More information about the Tutor mailing list