append to the end of a dictionary

Steven D'Aprano steve at REMOVETHIScyber.com.au
Tue Jan 24 16:15:04 EST 2006


On Tue, 24 Jan 2006 08:45:27 -0600, Tim Chase wrote:

> To get them in a key-order, my understanding is that you have to 
> use something like
> 
> 	keys = mydict.keys()
> 	sort(keys)
> 	orderedDict = [(k, mydict[k]) for k in keys]

Did you test this before posting?

>>> keys = ["a", "b"]
>>> sort(keys)
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
NameError: name 'sort' is not defined

sort is not a built-in function.

What you want is to call the sort method of the list:

keys.sort()

The sort method is always in-place, it does NOT return the newly sorted
list.

If you are using Python 2.4 or up, you can call the function sorted(keys)
which leaves the original list as is, creates a copy, and sorts the copy.


> unless you have a way of doing an in-line sort, in which you would be
> able to do something like
> 
>    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(). :(

Remember, list.sort() does NOT return the list. It returns None. What you
are doing there is sorting the keys, throwing the sorted list away, and
trying to iterate over None.


-- 
Steven.




More information about the Python-list mailing list