Why are there no ordered dictionaries?

Alex Martelli aleax at mail.comcast.net
Mon Nov 21 16:44:28 CET 2005

bonono at gmail.com <bonono at gmail.com> wrote:
> d = somedict_from_db()
> prefer=['f','a',b']
> def my_order(d):
>    for x in prefer:
>      if x in d: yield x
>    s = frozenset(prefer)
>    for x in d:
>      if x not in s: yield x

Yes, a much cleaner architecture (if you don't need any sorting on
non-preferred keys of d) than the ponderous general one I proposed.  A
'key' approach with this behavior would be:

def my_key(k):
    try: return prefer.index(k)
    except ValueError: return len(prefer)

Now, 'for x in sorted(d, key=my_key)' should be equivalent to 'for x in
my_order(d)' thanks to the stability of sorting when the 'key' callable
returns equal values.

Neither of these way-simpler approaches is (I suspect) optimal for
speed, in the unlikely event one cares about that.  The idea of
preprocessing the 'preferred' list once and for all outside of the
function (which I used heavily in my previous post) might yield some
speed-up, for example:

def my_key_fast(k, _aux=dict((k,i) for i,k in enumerate(prefer),
    return _aux.get(k, _l)

It's very unlikely that this situation warrants such optimization, of
course, I'm just "thinking aloud" about abstract possibilities.


More information about the Python-list mailing list