Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is python dict creation from list of tuples 3x slower than from kwargs

Tags:

People also ask

Which is faster list or tuple or dictionary in Python?

Tuples are faster than lists. We should use a Tuple instead of a List if we are defining a constant set of values and all we are ever going to do with it is iterate through it. If we need an array of elements to be used as dictionary keys, we can use Tuples.

Which is faster dict or list in Python?

A dictionary is 6.6 times faster than a list when we lookup in 100 items.

Which is faster list tuple or dict?

It is well-known that in Python tuples are faster than lists, and dicts are faster than objects.

Why is dict faster than list?

The reason is because a dictionary is a lookup, while a list is an iteration. Dictionary uses a hash lookup, while your list requires walking through the list until it finds the result from beginning to the result each time.


There are a couple of ways to construct a dictionary in python, for example:

keyvals = [('foo', 1), ('bar', 'bar'), ('baz', 100)]

dict(keyvals)

and

dkwargs = {'foo': 1, 'bar': 'bar', 'baz': 100}

dict(**dkwargs)

When you benchmark these

In [0]: %timeit dict(keyvals)
667 ns ± 38 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

In [1]: %timeit dict(**dkwargs)
225 ns ± 7.09 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

you see that the first method is almost 3x slower than the second. Why is this?