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

$ 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?


Solution 1:

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;-).

Solution 2:

d=dict() requires a lookup in locals() then globals() then __builtins__, d={} doesn't

Solution 3:

If people use (just) dict() over (just) {}, it's generally because they don't know about {} (which is quite a feat), or because they think it's clearer (which is subjective, but uncommon.)

There are things you can do with dict that you can't do with {}, though, such as pass it to something that expects a callable, like collections.defaultdict(dict). There's also the fact that you can call dict with keyword arguments, which some people prefer:

>>> dict(spam=1, ham=2)
{'ham': 2, 'spam': 1}

Personally, I prefer the dict literal syntax because it works better when you want to use keys that are not valid identifiers:

>>> dict(pass=1)
 File "<stdin>", line 1
    dict(pass=1)
        ^
SyntaxError: invalid syntax
>>> dict('ham and eggs'=1)
  File "<stdin>", line 1
SyntaxError: keyword can't be an expression

(and mixing styles just because some keys are not valid identifiers, yuck.)