differences between "d = dict()" and "d = {}"

tshepang picture tshepang · Apr 30, 2010 · Viewed 18.1k times · Source
$ python2.7 -m timeit 'd={}'
10000000 loops, best of 3: 0.0331 usec per loop
$ python2.7 -m timeit 'd=dict()'
1000000 loops, best of 3: 0.19 usec per loop

Why use one over the other?

Answer

Alex Martelli picture Alex Martelli · Apr 30, 2010

I'm one of those who prefers words to punctuation -- it's one of the reasons I've picked Python over Perl, for example. "Life is better without braces" (an old Python motto which went on a T-shirt with a cartoon of a smiling teenager;-), after all (originally intended to refer to braces vs indentation for grouping, of course, but, hey, braces are braces!-).

"Paying" some nanoseconds (for the purpose of using a clear, readable short word instead of braces, brackets and whatnots) is generally affordable (it's mostly the cost of lookups into the built-ins' namespace, a price you pay every time you use a built-in type or function, and you can mildly optimize it back by hoisting some lookups out of loops).

So, I'm generally the one who likes to write dict() for {}, list(L) in lieu of L[:] as well as list() for [], tuple() for (), and so on -- just a general style preference for pronounceable code. When I work on an existing codebase that uses a different style, or when my teammates in a new project have strong preferences the other way, I can accept that, of course (not without attempting a little evangelizing in the case of the teammates, though;-).