Skip to content

Commit 861ce5e

Browse files
authored
feat(post): python optimization, dictionaries
1 parent 2c318f2 commit 861ce5e

1 file changed

Lines changed: 44 additions & 0 deletions

File tree

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
---
2+
layout: post
3+
title: "Python Optimizations: Are Nested Dict's or Dict's with Tuples for Key's quicker?"
4+
tags: software python speed-test optimization
5+
---
6+
7+
`Dict[Dict[Any, Any]]` vs Dict[Tuple[Any, Any]]
8+
9+
Which is faster in python? A Dict with tuples as keys or a dict of dict's? TLDR: A dict of tuples, but only by a little bit!
10+
11+
The test:
12+
13+
```
14+
from timeit import timeit
15+
16+
def dict_test():
17+
d = {}
18+
for i in range(1, 1000):
19+
d[(i, i*5)] = i
20+
21+
for i in range(1,1000):
22+
d[(i, i*5)]
23+
24+
def dict_test2():
25+
d = {}
26+
for i in range(1, 1000):
27+
if i not in d:
28+
d[i] = {}
29+
d[i][i*5] = i
30+
31+
for i in range(1,1000):
32+
d[i][i*5]
33+
34+
35+
print("dict_test took: {}s".format(timeit(dict_test, number=10000)))
36+
print("dict_test2 took: {}s".format(timeit(dict_test2, number=10000)))
37+
```
38+
39+
The result:
40+
41+
```
42+
dict_test took: 3.9785058770678177s
43+
dict_test2 took: 4.405024016745074s
44+
```

0 commit comments

Comments
 (0)