Reverting Columns of a 2D Iterable

Every now and then I "discover" a cute one-liner data transformation idiom. Here is one to revert the order of columns in a 2-D iterable. It comes in handy to invert a dictionary (i.e. to swap keys and values).


I used this for unescaping XML/HTML, in order to derive the reverse entity mapping from a given "forward" mapping (most notably: htmlentitydefs.entitydefs). See the python documentation on xml.sax.saxutils' escape and unescape functions for more information.

Cheers and happy column reverting.

# the idiom:

def theIdiom(a2Diterable): 
  return zip(*reversed(zip(*a2Diterable))) 

# sample use case:

def invertedDict(aDict):
  return dict(zip(*reversed(zip(*aDict.items()))))

code.activestate.com ↗