Sort a Dictionary

mackstann mack at incise.org
Fri Aug 22 22:24:53 EDT 2003


On Sat, Aug 23, 2003 at 02:03:09AM +0000, Afanasiy wrote:
> This is fairly simple in PHP, how do I do it in Python?

In PHP, associative arrays are still regular arrays too, you can access
them by index (IIRC), and when you loop through them, they maintain the
order in which you assigned their items. Python seperates associative
arrays (dicts/hashes) from numerically indexed arrays (lists).  You
can't sort a dict, because a dict has no order.  You could do something
like:

mydict = { ..whatever.. }

sortedkeys = mydict.keys()
sortedkeys.sort()

for key in sortedkeys:
  print key, mydict[key]

Then we run into the issue of why we have to do list.sort() in place,
and I'm sure that's been discussed here a billion times (can't say I've
been part of any of those discussions though).

-- 
m a c k s t a n n  mack @ incise.org  http://incise.org
After a few boring years, socially meaningful rock 'n' roll died out.
It was replaced by disco, which offers no guidance to any form of life
more advanced than the lichen family.
		-- Dave Barry, "Kids Today: They Don't Know Dum Diddly Do"





More information about the Python-list mailing list