Mark Gritter (markgritter) wrote,
Mark Gritter

Python mini-recipe

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? ;)
Tags: programming, python
  • Post a new comment


    default userpic

    Your reply will be screened

    Your IP address will be recorded 

    When you submit the form an invisible reCAPTCHA check will be performed.
    You must follow the Privacy Policy and Google Terms of use.