Order of elements in a dict

Paul McGuire ptmcg at austin.rr.com
Tue Apr 26 05:56:46 EDT 2005


Here is a brute-force list comprehension that does not depend on
preserving order between dict.keys() and dict.values():

dict( [ (a[1],a[0]) for a in d.items() ] )

Or for map/lambda lovers:

rev = lambda a: (a[1],a[0])
dict( map( rev, d.items() )

But you still have no control over the order returned by d.items(), so
if your initial dict has duplicate values, there is no telling which
key a duplicate would map to.

The real general-purpose dict inversion results in a dict with each
value containing a list of keys in the original dict that mapped to the
given value.  That is:
    d = {3: 4, 1: 2, 0:4}
would invert to:
    d2 = { 2:[1], 4:[0,3] }

I couldn't cram this into a list comp, so here is a short for loop to
create d2:
d2 = {}
for k,v in d.items():
    d2[v] = d2.get(v, list()) + [k]

-- Paul




More information about the Python-list mailing list