How to sort using hash's key?

Ben Finney bignose+hates-spam at benfinney.id.au
Wed Jan 31 19:24:09 EST 2007


Steven Bethard <steven.bethard at gmail.com> writes:

> JoJo wrote:
> > I want to sort a dict via its key,but I have no idea on how to do
> > it.
>
> >>> d = dict(a=2, b=1)
> >>> for key in sorted(d):
> ...     print key, d[key]
> ...
> a 2
> b 1

That's not a solution to "sort the dict"; that's getting a particular
representation of the dict. It's likely the original poster wants the
equivalent to list.sort() instead of a one-time output of the
contents.

-- 
 \        "I installed a skylight in my apartment. The people who live |
  `\                          above me are furious!"  -- Steven Wright |
_o__)                                                                  |
Ben Finney




More information about the Python-list mailing list