Feb 11, 2008 21:04
Here's a line of python code to turn a 1-1 dictionary fwdMap into its inverse.
revMap = dict( [ tuple( reversed( x ) ) for x in fwdMap.items() ] )
Is there a better version? Well, tuple/reversed is overkill for a two-element tuple; this version is a bit shorter but I hate using indices.
revMap = dict( [ (x[1],x[0]) for x in fwdMap.items() ] )
A little searching on Google turned up this much better version which tells me I still am not properly internalizing list comprehension syntax:
revMap = dict( [ (x, y) for y, x in fwdMap.iteritems() ] )
I'm not sure how much using the iterator instead of a temporary list actually buys you. Shouldn't an optimizing compiler generate the same code in either case? ;)
python,
programming