I was reading the following topic: Make dictionary from list with python
The initial problem is to transform the tuple (1,'a',2,'b',3,'c')
into the dictionary {1: 'a', 2: 'b', 3: 'c'}
. Many interesting solutions were given, including the following two:
Solution 1:
dict(x[i:i+2] for i in range(0, len(x), 2))
Solution 2:
dict(zip(*[iter(val_)] * 2))
In solution 1, why bother creating the actual list with range
? Wouldn't xrange( 0, len(x), 2 )
be more memory efficient? Same question for solution 2: zip
creates an actual list. Why not using itertools.izip
instead?
As far as I know
is the usual "Pythonic" way of doing it. And the approach in Python when it comes to optimizing stuff is to always profile and see where time is being spent. If the above approach works fine for your application, why optimize it?