28

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
  • 35,525
  • 9
  • 94
  • 135
prosseek
  • 169,389
  • 197
  • 542
  • 840

5 Answers5

40
dict(x[i:i+2] for i in range(0, len(x), 2))
Alex Martelli
  • 811,175
  • 162
  • 1,198
  • 1,373
  • 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

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
  • 281,034
  • 50
  • 354
  • 495
11
dict(zip(*[iter(val_)] * 2))
Ignacio Vazquez-Abrams
  • 740,318
  • 145
  • 1,296
  • 1,325
11
>>> x=(1,'a',2,'b',3,'c')
>>> dict(zip(x[::2],x[1::2]))
{1: 'a', 2: 'b', 3: 'c'}
Mark Tolonen
  • 148,243
  • 22
  • 160
  • 229
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
  • 205,639
  • 55
  • 286
  • 290