Convert a single ordered list in python to a dictionary, pythonically

I cannot find an elegant way to start with t and lead to s.

>>>t = ['a',2,'b',3,'c',4]
#magic
>>>print s
{'a': 2, 'c': 4, 'b': 3}

The solutions I came up with seem less elegant:

s = dict()
for i in xrange(0, len(t),2): s[t[i]]=t[i+1]
# or something fancy with slices that I haven't figured out yet

Obviously, it is easily solved, but, again, it seems that there is a better way. There is?

+1
source share
6 answers

I would use it itertools, but if you find it difficult (as you hinted at at the comment), then it’s possible:

def twobytwo(t):
  it = iter(t)
  for x in it:
    yield x, next(it)

d = dict(twobytwo(t))

or equivalent, and return to itertools again,

def twobytwo(t):
  a, b = itertools.tee(iter(t))
  next(b)
  return itertools.izip(a, b)

d = dict(twobytwo(t))

or, if you insist on being inbuilt, in a suitable “trick or treat” mood season:

d = dict((x, next(it)) for it in (iter(t),) for x in it)

, , , . IOW, , , , : -).

, , " 2 ", dict 2- . , , O(1) ( , O(N), dict, ).

docs ( , itertool) - pairwise on , , . , - iterutils.py (, python stdlib!).

+10

, , :

>>> dict(zip(*([iter(t)] * 2)))
{'a': 2, 'c': 4, 'b': 3}

dict, zip iter. , . :

  • iter(t) t.
  • [iter(t)] * 2 , .
  • zip - , : , .. , .
  • zip(*([iter(t)] * 2)) , t zip. zip, , t . . , ..
  • dict , (key, value) .
  • dict(zip(*([iter(t)] * 2))) OP.
+9

, :

dict(zip(t[::2], t[1::2]))

:

dict(t[i:i+2] for i in xrange(0, len(t), 2))
+7

, , itertools. , .

>>> from itertools import izip, islice
>>> t = ['a',2,'b',3,'c',4]
>>> s = dict(izip(islice(t, 0, None, 2), islice(t, 1, None, 2)))
>>> s
{'a': 2, 'c': 4, 'b': 3}

, .

+6
source

Using the stream module :

>>> from stream import chop
>>> t = ['a',2,'b',3,'c',4]
>>> s = t >> chop(2) >> dict
>>> s
{'a': 2, 'c': 4, 'b': 3}

It should be noted that this module is rather obscure and does not actually “play by the rules” of what is generally considered politically correct Python. Therefore, if you are just learning Python, do not go this route; stick to what's in the standard library.

+2
source
dict(zip(t[::2], t[1::2]))

probably not the most effective. works in python 3; you may need to import zip in python 2.x

+1
source

All Articles