Dict comprehensions - improvement to docs?

Frank Millman frank at chagford.com
Mon Mar 16 05:01:22 EDT 2015


"Paul Rubin" <no.email at nospam.invalid> wrote in message 
news:87wq2hfibu.fsf at jester.gateway.sonic.net...
> "Frank Millman" <frank at chagford.com> writes:
>> dict((a, b) for a, b in zip(x, y))
>> 100000 loops, best of 3: 16.1 usec per loop
>> {a: b for a, b in zip(x, y)}"
>> 100000 loops, best of 3: 6.38 usec per loop
>
> Hmm, I bet the difference is from the (a,b) consing all those tuples.
>
> Can you try just dict(zip(x,y))  ?

C:\>python -m timeit -s "x = range(65, 91); y = (chr(z) for z in x)" 
"dict(zip(x, y))"
100000 loops, best of 3: 11.9 usec per loop

C:\>python -m timeit -s "x = range(65, 91); y = (chr(z) for z in x)" "{a: b 
for a, b in zip(x, y)}"
100000 loops, best of 3: 7.24 usec per loop

I ran the dict comp again in case the machine load had changed - it is a bit 
slower, but not much.

Frank






More information about the Python-list mailing list