append to the end of a dictionary

Tim Chase python.list at
Tue Jan 24 15:45:27 CET 2006

> I seem to be unable to find a way to appends more keys/values to the end 
> of a dictionary... how can I do that?
> E.g:
> mydict = {'a':'1'}
> I need to append 'b':'2' to it to have:
> mydict = {'a':'1','b':'2'}

my understanding is that the order of a dictionary should never 
be relied upon.  To do what you want, you'd use

	mydict['b'] = '2'

However, you're just as liable to get

	>>> mydict

as you are to get

	>>> mydict

To get them in a key-order, my understanding is that you have to 
use something like

	keys = mydict.keys()
	orderedDict = [(k, mydict[k]) for k in keys]

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(). :(


More information about the Python-list mailing list