Tim Chase wrote:
> > 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()]
>

You can do all this and more from the OrderedDict in pythonutils :


    http://www.voidspace.org.uk/python/odict.html
    http://www.voidspace.org.uk/python/pythonutils.html

from odict import OrderedDict

our_dict = OrderedDict(some_dict.items())
our_dict.sort()

All the best,

Fuzzyman
http://www.voidspace.org.uk/python/index.shtml

> Unfortunately, the version I've got here doesn't seem to support
> a sort() method for the list returned by keys(). :(
> 
> -tim

-- 
http://mail.python.org/mailman/listinfo/python-list

Reply via email to