[Tutor] Is there a programmatic use for keys() and values()

Steven D'Aprano steve at pearwood.info
Sun Jun 16 20:28:08 CEST 2013


On 17/06/13 03:25, Jim Mooney wrote:
> On 15 June 2013 23:30, Dave Angel <davea at davea.name> wrote:
>
>>>> The sort() method doesn't work, but sorted does.
>
> How many times have I read you can't sort a dictionary in Python. Was
> I just misreading or was that true of older Pythons?

You can't sort a dictionary, because dicts don't have any inherent order. (Unlike paper dictionaries.) That's done for performance reasons.

However, if you extract the keys from a dict, you can sort the keys separately.

So mydict.sort() fails, since dicts can't be sorted. But:

keys = list(mydict.keys())
keys.sort()

works fine. And here's something which, at first glance, *appears* to be sorting a dict, but actually isn't:

sorted(mydict)
=> returns a list of mydict's keys, sorted.



-- 
Steven


More information about the Tutor mailing list