29

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 

A better way to get the same results?

ADDED

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

seems to be working

Aran-Fey
  • 39,665
  • 11
  • 104
  • 149
prosseek
  • 182,215
  • 215
  • 566
  • 871

5 Answers5

41
dict(x[i:i+2] for i in range(0, len(x), 2))
Alex Martelli
  • 854,459
  • 170
  • 1,222
  • 1,395
  • 5
    Can you please explain this answer. – RamPrasadBismil Jun 15 '15 at 23:32
  • 5
    @user2601010, it's just using some elementary building blocks of Python -- calling `dict` (with a sequence of 2-item "pairs") to build a dictionary, slicing a list, a generator expression, and the `range` built-in. Which of these four elementary concepts are unclear to you? (My book "Python in a Nutshell" of course explains all of them, and, many more besides, but, its whole text would not fit in a comment:-). – Alex Martelli Jun 16 '15 at 20:45
12
dict(zip(*[iter(val_)] * 2))
Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
12

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'}
John La Rooy
  • 295,403
  • 53
  • 369
  • 502
11
>>> x=(1,'a',2,'b',3,'c')
>>> dict(zip(x[::2],x[1::2]))
{1: 'a', 2: 'b', 3: 'c'}
Mark Tolonen
  • 166,664
  • 26
  • 169
  • 251
4
x = (1,'a',2,'b',3,'c') 
d = dict(x[n:n+2] for n in xrange(0, len(x), 2))
print d
nosklo
  • 217,122
  • 57
  • 293
  • 297