Sorting dict keys
Alex Popescu
nospam.themindstorm at gmail.com
Fri Jul 20 19:55:56 EDT 2007
Miles <semanticist at gmail.com> wrote in
news:a49e45f50707201627n524f6a49n13f2ca97f55d4133 at mail.gmail.com:
> 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
You are absolutely right about both points (it looks like answering python
question very late in the evening doesn't work well for me, or at least not
yet :-)).
./alex
--
.w( the_mindstorm )p.
More information about the Python-list
mailing list