Convert a list to a dictionary in Python

前端 未结 12 2147
無奈伤痛
無奈伤痛 2020-11-22 04:14

Let\'s say I have a list a in Python whose entries conveniently map to a dictionary. Each even element represents the key to the dictionary, and the following o

12条回答
  •  梦如初夏
    2020-11-22 05:07

    You can do it pretty fast without creating extra arrays, so this will work even for very large arrays:

    dict(izip(*([iter(a)]*2)))
    

    If you have a generator a, even better:

    dict(izip(*([a]*2)))
    

    Here's the rundown:

    iter(h)    #create an iterator from the array, no copies here
    []*2       #creates an array with two copies of the same iterator, the trick
    izip(*())  #consumes the two iterators creating a tuple
    dict()     #puts the tuples into key,value of the dictionary
    

提交回复
热议问题