Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is the dict literal syntax preferred over the dict constructor?

Why is the Python dict constructor slower than the using literal syntax?

After hot debate with my colleague, I did some comparison and got the following statistics:

python2.7 -m timeit "d = dict(x=1, y=2, z=3)" 1000000 loops, best of 3: 0.47 usec per loop  python2.7 -m timeit "d = {'x': 1, 'y': 2, 'z': 3}" 10000000 loops, best of 3: 0.162 usec per loop 

What is the reason the constructor is slower? And in what situations, if any, would it be faster?

like image 611
Fabz Avatar asked Oct 10 '14 23:10

Fabz


People also ask

Should I use dict () or {}?

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.

What is a dict constructor?

Python Language Dictionary The dict() constructor The dict() constructor can be used to create dictionaries from keyword arguments, or from a single iterable of key-value pairs, or from a single dictionary and keyword arguments.

What is dictionary literal in Python?

A dict literal is created by surrounding a key-value list with {} 's; a keys is separated from its value with : 's, and the key : value pairs are separated with commas ( , ). An empty dict is simply {} . As with list s and tuple s, an extra , inside the {} 's is tolerated.

What is dict constructor in Python?

The dict() constructor creates a dictionary in Python. Different forms of dict() constructors are: class dict(**kwarg) class dict(mapping, **kwarg) class dict(iterable, **kwarg) Note: **kwarg let you take an arbitrary number of keyword arguments. A keyword argument is an argument preceded by an identifier (eg. name= ).


1 Answers

The constructor is slower because it creates the object by calling the dict() function, whereas the compiler turns the dict literal into BUILD_MAP bytecode, saving the function call.

like image 138
Ignacio Vazquez-Abrams Avatar answered Sep 22 '22 09:09

Ignacio Vazquez-Abrams