What is the preferred syntax for initializing a dict: curly brace literals {} or the dict() function?
Curly braces. Passing keyword arguments into dict()
, though it works beautifully in a lot of scenarios, can only initialize a map if the keys are valid Python identifiers.
This works:
a = {'import': 'trade', 1: 7.8}
a = dict({'import': 'trade', 1: 7.8})
This won't work:
a = dict(import='trade', 1=7.8)
It will result in the following error:
a = dict(import='trade', 1=7.8)
^
SyntaxError: invalid syntax
The first, curly braces. Otherwise, you run into consistency issues with keys that have odd characters in them, like =
.
# Works fine.
a = {
'a': 'value',
'b=c': 'value',
}
# Eeep! Breaks if trying to be consistent.
b = dict(
a='value',
b=c='value',
)
The first version is preferable:
- It works for all kinds of keys, so you can, for example, say
{1: 'one', 2: 'two'}
. The second variant only works for (some) string keys. Using different kinds of syntax depending on the type of the keys would be an unnecessary inconsistency. It is faster:
$ python -m timeit "dict(a='value', another='value')" 1000000 loops, best of 3: 0.79 usec per loop $ python -m timeit "{'a': 'value','another': 'value'}" 1000000 loops, best of 3: 0.305 usec per loop
- If the special syntax for dictionary literals wasn't intended to be used, it probably wouldn't exist.