append to the end of a dictionary
Tim Chase
python.list at tim.thechases.com
Tue Jan 24 11:18:50 EST 2006
>> orderedDict = [(k,mydict[k]) for k in mydict.keys().sort()]
>>
>>Unfortunately, the version I've got here doesn't seem to support
>>a sort() method for the list returned by keys(). :(
>
> I bet it does, but it doesn't do what you think it does. See
> http://docs.python.org/lib/typesseq-mutable.html , in particular
> note 7.
>
> What you want is the sorted() function (introduced in 2.4 IIRC).
Kinda thought so. Yes...the sort() function doesn't return the
results, but rather sorts in-place and returns nothing. The
sorted() function was what I was reaching for, but only having
2.3.5 on the server at my finger tips, I couldn't verify that.
So yes, it looks like the answer would be
orderedDict = [(k,mydict[k]) for k in mydict.keys().sorted()]
List comprehensions are such lovely things... :)
-tkc
More information about the Python-list
mailing list