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).
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.
I find it more readable, and more or less as concise, to use generator expressions:
maybe using reversed instead of explicit unpacking in some cases.
Whoops, stupid error. It should obviously be
Right,... I admit,
does the job equally well. Thx.
(Now you made me wonder if I've got a addiction to pre-generator map/filter/reduce idioms... ;-)