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

前端 未结 6 767
悲&欢浪女
悲&欢浪女 2021-01-07 14:00

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
         


        
6条回答
  •  春和景丽
    2021-01-07 14:39

    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:

    1. iter(t) creates an iterator over the list t.
    2. [iter(t)] * 2 creates a list with two elements, which reference the same iterator.
    3. 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.
    4. 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.
    5. dict takes an iterable containing (key, value) pairs and creates a dctionary out of them.
    6. dict(zip(*([iter(t)] * 2))) creates the dictionary as requested by the OP.

提交回复
热议问题