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?

0

5 Answers 5

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

7
  • 1
    "hoisting some lookups out of loops" - what this mean?
    – tshepang
    Apr 30, 2010 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. Apr 30, 2010 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, 2010 at 16:56
  • @AlexMartelli What about s=str() vs. s=''?
    – tshepang
    Feb 3, 2016 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. Feb 8, 2016 at 14:46
24

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

2
  • Nope, dict is in __builtin__. Apr 30, 2010 at 15:13
  • @MikeGraham yes but in most cases __builtins__ is an alias for __builtin__
    – jamylak
    Jun 3, 2013 at 10:39
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.)

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.

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.