append to the end of a dictionary
Tim Chase
python.list at tim.thechases.com
Tue Jan 24 09:45:27 EST 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
{'a':'1','b':'2'}
as you are to get
>>> mydict
{'b':'2','a':'1'}
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]
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(). :(
-tim
More information about the Python-list
mailing list