Monday, July 2, 2012

Swap keys and values in a Python dictionary

Many options exist to swap or exchange keys and values in a Python dict() object (dictionary). Prior to creating a new dictionary of (value, key) pairs, it's worthwhile to check that


len( set( d.values() ) ) == len( d.values() )


Anyway, options: 
  1. pairs = zip(d.values(), d.keys())
  2. pairs = zip(d.itervalues(), d.iterkeys())
  3. pairs = [(v, k) for (k, v) in d.iteritems()]
And to create a dictionary, just throw dict() around the zip() or list brackets.