[EMAIL PROTECTED] <[EMAIL PROTECTED]> 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), _l=len(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. Alex -- http://mail.python.org/mailman/listinfo/python-list