Welcome, guest | Sign In | My Account | Store | Cart

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).

Python, 9 lines
1
2
3
4
5
6
7
8
9
# the idiom:

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

# sample use case:

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

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.

3 comments

Matteo Dell'Amico 16 years, 8 months ago  # | flag

I find it more readable, and more or less as concise, to use generator expressions:

def invertedDict(d):
    return dict((k, v) for k, v in d.iteritems())

maybe using reversed instead of explicit unpacking in some cases.

Matteo Dell'Amico 16 years, 8 months ago  # | flag

Whoops, stupid error. It should obviously be

def invertedDict(d):
    return dict((v, k) for k, v in d.iteritems())
Zoran Isailovski (author) 16 years, 8 months ago  # | flag

Right,... I admit,

[ tuple(reversed(row)) for row in iterable ]

does the job equally well. Thx.

(Now you made me wonder if I've got a addiction to pre-generator map/filter/reduce idioms... ;-)

Created by Zoran Isailovski on Tue, 17 Jul 2007 (PSF)
Python recipes (4591)
Zoran Isailovski's recipes (13)

Required Modules

  • (none specified)

Other Information and Tasks