Sorting dict keys

Miles semanticist at gmail.com
Fri Jul 20 19:27:50 EDT 2007


On 7/20/07, Alex Popescu <nospam.themindstorm at gmail.com> wrote:
> If you just want to iterate over your dict in an ordered manner than all
> you have to do is:
>
> for k in my_dict.keys().sort():
>   # rest of the code

I think you meant sorted(my_dict.keys()), since, as you just pointed
out, the sort() method returns None.

> If you just want to keep a list of ordered keys you can probably do
> something like:
>
> key_list = list(my_dict.keys())
> key_list.sort()

Creating a copy with list() is unnecessary, as keys() already returns a copy.

-Miles



More information about the Python-list mailing list