Dictionary from a list

Peter Otten __peter__ at web.de
Thu Aug 20 08:10:28 CEST 2009


Jan Kaliszewski wrote:

> 20-08-2009 o 02:05:57 Jan Kaliszewski <zuo at chopin.edu.pl> wrote:
> 
>> Or probably better:
>>
>>      from itertools import islice, izip
>>      dict(izip(islice(li, 0, None, 2), islice(li, 1, None, 2)))
> 
> Or similarly, perhaps more readable:
> 
>      iterator = iter(li)
>      dict((iterator.next(), iterator.next()) for i in xrange(len(li)/2))

I just can't stop posting this one:

>>> from itertools import izip
>>> it = iter([1,2,3,4,5,6])
>>> dict(izip(it, it))
{1: 2, 3: 4, 5: 6}

I really tried, but yours drove me over the edge.

Peter




More information about the Python-list mailing list