How to sort using hash's key?
Steven Bethard
steven.bethard at gmail.com
Wed Jan 31 23:23:26 EST 2007
Ben Finney wrote:
> 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.
Yes, but as others have pointed out, you can't get that with a standard
Python dict. 99% of the time when a poster asks about how to sort a
dict, their problem can be solved by simply sorting the dict keys or values.
STeVe
More information about the Python-list
mailing list