Re: append to the end of a dictionary




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

.



Relevant Pages

  • Re: Talking of old jokes
    ... I'm familiar with MeChA which used the word and concept Reconquista in an idealistic or spiritual fashion. ... Sort of like not understanding the difference between the thing and its symbolic representation. ...
    (rec.arts.sf.fandom)
  • Re: Problem with nested for-loops
    ... Getting solid rules about what is and is not permitted is essential to ... that understanding. ... recursive functions. ... I'm sorry to be so sort on these comments but I'm in quite a rush. ...
    (comp.theory)
  • Re: Iran declares victory
    ... who seems soooo clueless (incl. ... this sort of thing - not truly ... understanding that others may not want to dilute their own culture & be ...
    (alt.autos.toyota)
  • Re: What Edser exemplifies explicitly, and all but one of all other sbe-participants exemplify i
    ... > Aside from the fact that the discernable portion of Peter's ramblings is ... > simply a sort of sophomoric Freudianism mixed with a sophomoric ... > understanding of avoidance conditioning and phobias, ...
    (sci.bio.evolution)