I can\'t seem to find an elegant way to start from t and result in s.
>>>t = [\'a\',2,\'b\',3,\'c\',4]
#magic
>>>print s
Same idea as Lukáš Lalinský's answer, different idiom:
>>> dict(zip(*([iter(t)] * 2)))
{'a': 2, 'c': 4, 'b': 3}
This uses the dict, zip and iter functions. It's advantage over Lukáš' answer is that it works for any iterable. How it works:
iter(t)
creates an iterator over the list t
.[iter(t)] * 2
creates a list with two elements, which reference the same iterator.zip
is a function which take two iterable objects and pairs their elements: the first elements together, the second elements together, etc., until one iterable is exhausted.zip(*([iter(t)] * 2))
causes the same iterator over t
to be passed as both arguments to zip
. zip
will thus take the first and second element of t
and pair them up. And then the third and fourth. And then the fifth and sixth, etc.dict
takes an iterable containing (key, value)
pairs and creates a dctionary out of them.dict(zip(*([iter(t)] * 2)))
creates the dictionary as requested by the OP.