Two-dimensional version of one-dimensional dictionary efficiency in Python

Which is more efficient in terms of memory and speed between

d[(first,second)]

and

d[first][second],

where dis the dictionary of either tuples or dictionaries?

+5
source share
2 answers

Here are some very simple test data that shows that for a very far-fetched example (storing "a" a million times using numbers as keys) using 2 dictionaries is significantly faster.

$ python -m timeit 'd = {i:{j:"a" for j in range(1000)} for i in range(1000)};a = [d[i][j] for j in range(1000) for i in range(1000)];'
10 loops, best of 3: 316 msec per loop
$ python -m timeit 'd = {(i, j):"a" for j in range(1000) for i in range(1000)};a = [d[i, j] for j in range(1000) for i in range(1000)];'
10 loops, best of 3: 970 msec per loop

Of course, these tests do not necessarily mean anything, depending on what you are trying to do. Determine what you will store, and then check.

A bit more data:

$ python -m timeit 'a = [(hash(i), hash(j)) for i in range(1000) for j in range(1000)]'
10 loops, best of 3: 304 msec per loop
$ python -m timeit 'a = [hash((i, j)) for i in range(1000) for j in range(1000)]'
10 loops, best of 3: 172 msec per loop
$ python -m timeit 'd = {i:{j:"a" for j in range(1000)} for i in range(1000)}'
10 loops, best of 3: 101 msec per loop
$ python -m timeit 'd = {(i, j):"a" for j in range(1000) for i in range(1000)}'
10 loops, best of 3: 645 msec per loop

, , , . , . , .

+5

, , CPython 2.7, Pypy 1.8.

, ps.

+1

All Articles