views:

87

answers:

5

I need to transform a list into dictionary as follows. The odd elements has the key, and even number elements has the value.

x = (1,'a',2,'b',3,'c') -> {1: 'a', 2: 'b', 3: 'c'}
def set(self, val_): 
        i = 0 
        for val in val_: 
            if i == 0: 
                i = 1 
                key = val 
            else: 
                i = 0 
                self.dict[key] = val 

My solution seems to long, is there a better way to get the same results?

== ADDED ==

i = iter(k)
print dict(zip(i,i))

seems to be working

A: 
x = (1,'a',2,'b',3,'c') 
d = dict(x[n:n+2] for n in xrange(0, len(x), 2))
print d
nosklo
Yay I'm the fastest!! :D
nosklo
+3  A: 
dict(x[i:i+2] for i in range(0, len(x), 2))
Alex Martelli
A: 
dict(zip(*[iter(val_)] * 2))
Ignacio Vazquez-Abrams
A: 

Here are a couple of ways for Python3 using dict comprehensions

>>> x = (1,'a',2,'b',3,'c')
>>> {k:v for k,v in zip(*[iter(x)]*2)}
{1: 'a', 2: 'b', 3: 'c'}
>>> {x[i]:x[i+1] for i in range(0,len(x),2)}
{1: 'a', 2: 'b', 3: 'c'}
gnibbler
+1  A: 
>>> x=(1,'a',2,'b',3,'c')
>>> dict(zip(x[::2],x[1::2]))
{1: 'a', 2: 'b', 3: 'c'}
Mark Tolonen
Using timeit module, this seems to be fastest method also, so far anyway :)
Mark Tolonen
Correction, gnibbler's dict comps are both faster on my system (2.58us,3.51us), and mine got slower on Python3.1.2 (4.75us vs. Python2.6.5 4us).
Mark Tolonen