Python mini-recipe

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 ( Read more... )

python, programming

Leave a comment

Comments 2

ckd February 12 2008, 05:21:05 UTC
I think that's a bit much to ask of an optimizing compiler that's compiling to byte code and not native code.

For small dictionaries, the iterator doesn't buy you much. It's when you start getting into bigger lists (or smaller machines) that it really wins; that fwdMap might be a big on-disk bsddb database, after all.

Reply

markgritter February 12 2008, 05:25:00 UTC
I expect _more_ from an optimizing compiler that's generating byte code since it doesn't have any funny instruction set scheduling to worry about. :)

I think data flow analysis should be able to figure out what's going on here and elide the temporary. The problem is that "allocate memory" is a side effect--- one that, perhaps, the programmer wanted. But that's just a matter of defining your programming language semantics the right way...

Reply


Leave a comment

Up