Ordered dict by default

Paul Rubin http
Thu Feb 5 06:25:52 EST 2009


Duncan Booth <duncan.booth at invalid.invalid> writes:
> If you want to write doctests then any stable order in the default dict 
> type would be helpful no matter whether it means that keys are in original 
> insertion or latest insertion order or sorted.

Just use "sorted" in the test code:
  >>> print sorted(dict((a**2,a) for a in xrange(5)).keys())
  [0, 1, 4, 9, 16]

> There are other use cases where maintaining insertion order is
> important.  For example any automated code generator which parses
> its previous output and then regenerates it maintaining edits. I ran
> into that before with one which just stored the methods in a Python
> dict so that every so often you'd find the entire source file had
> rearranged itself making a mess of version control.

Still doesn't sound so bad: just include a counter with the value.
Something like (untested):

   odict = dict(zip(methodnames, zip(methodbodies, itertools.count())))
   ...
   gen_code(sorted(odict.iteritems(), key=lambda(name,(body,n)): n))

> It would certainly be an interesting experiment to mimic the Ruby dict 
> implementation in Python's dict code and see what effect it has on 
> performance: the Ruby page claims that while inserts are slower traversal 
> is much faster. I think it would need some pretty convincing arguments 
> though to become the default.

In my usage of dicts, traversal is rather rare, but YMMV.



More information about the Python-list mailing list