Dict comprehensions - improvement to docs?

Frank Millman frank at chagford.com
Mon Mar 16 04:30:50 EDT 2015


"Paul Rubin" <no.email at nospam.invalid> wrote in message 
news:87fv95fom0.fsf at jester.gateway.sonic.net...
> "Frank Millman" <frank at chagford.com> writes:
>> I like dict comprehensions, but I don't use them very often, so when I do 
>> I
>> need to look up the format.
>
> I never felt a need for them.  Do they generate better code than
>
>   d = dict((k,v) for k,v in [('name','paul'),('language','python')])  ?
>

I ran timeit, and dict comps are quite a bit quicker. This is with Python 
3.4.1 -

C:\>python -m timeit -s "x=range(65, 91); y=(chr(z) for z in x)" "dict((a, 
b) for a, b in zip(x, y))"
100000 loops, best of 3: 16.1 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: 6.38 usec per loop

Frank






More information about the Python-list mailing list