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

suci
  • 178
  • 7
tshepang
  • 12,111
  • 21
  • 91
  • 136

5 Answers5

60

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

Alex Martelli
  • 854,459
  • 170
  • 1,222
  • 1,395
  • 1
    "hoisting some lookups out of loops" - what this mean? – tshepang Apr 30 '10 at 15:48
  • 10
    @Tshepang, e.g. instead of `for i in x: f(dict())` (which does `len(x)` lookups for name `dict`), first bind a local `d=dict` outside the loop, then `for i in x: f(d())` which does a faster _local_ lookup for name `d`). It's a fundamental Python technique to optimize some loops when they're proven (by profiling, of course) to be performance bottlenecks. – Alex Martelli Apr 30 '10 at 16:25
  • 1
    Incidentally (and not related to this question at all, of course), Unladen Swallow should make this kind of idiom (d=dict) unnecessary :) – rbp Apr 30 '10 at 16:56
  • @AlexMartelli What about `s=str()` vs. `s=''`? – tshepang Feb 03 '16 at 12:16
  • I wouldn't use `str()` in lieu of `''` any more than `int()` in lieu of `0` -- that wouldn't promote "pronounceable code" nor reduce punctuation. – Alex Martelli Feb 08 '16 at 14:46
  • In addition to readability I also don't like that there is no sort of `{}` idiom for empty sets, so there is an uncomfortable asymmetry going on there. For empty collections, you have `[]` for `list()`, `{}` for `dict()`, and even `()` for `tuple()`, but nothing like that for `set()`. – André C. Andersen Apr 09 '17 at 18:56
  • You can't have a diploid punctuation character for every complex type! dict list and tuple are the core types that are supported. But I think I feel that dict() vs braces is somehow more Pythonic because it minimises language elements, so I empathise, but given these are the 3 most common ubiquitous complex types, and there is a 5x speed improvement, I prefer to use braces. How you can think making a local reference with d=dict improves readability or simplicity I don't know. Just use braces! – NeilG May 14 '19 at 13:09
24

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

Uli Köhler
  • 13,012
  • 16
  • 70
  • 120
John La Rooy
  • 295,403
  • 53
  • 369
  • 502
10

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

Thomas Wouters
  • 130,178
  • 23
  • 148
  • 122
7

Doug Hellmann wrote up an exhaustive comparison of the performance difference.

tl;dr

With CPython 2.7, using dict() to create dictionaries takes up to 6 times longer and involves more memory allocation operations than the literal syntax. Use {} to create dictionaries, especially if you are pre-populating them, unless the literal syntax does not work for your case.

sanyassh
  • 8,100
  • 13
  • 36
  • 70
George V. Reilly
  • 15,885
  • 7
  • 43
  • 38
1

Like Thomas said, I use dict() so I can specify keywords. Especially if I'm manually constructing a large dictionary for data initialization or whatnot: being able to use keyword syntax saves me two keystrokes (and the associated visual clutter) for every element.

Vicki Laidler
  • 3,415
  • 1
  • 20
  • 17