I noticed that, in many cases, retrieving data from nested dictionaries is much faster than from dictionaries with tuple keys. This seems to contradict what was said here. Can anyone please explain what causes this? My issue is that the faster way seems less "pythonic" and can lead to huge ugly nested dictionaries (e.g. a_dict[a][b][c][d] instead of a_dict[a,b,c,d]).
Below is an example where this occurs when using integers as keys:
Using tuples:
print timeit.timeit('''
for (int1, int2) in indexes:
x[ int1, int2 ]
''', setup='''
x={}
indexes = []
for int1 in xrange(1000):
for int2 in xrange(1000):
x[ int1, int2 ] = 'asd'
indexes.append((int1, int2))
''', number = 100)
Using nested dictionaries:
print timeit.timeit('''
for (int1, int2) in indexes:
x[int1][ int2 ]
''', setup='''
x={}
indexes = []
for int1 in xrange(1000):
x[int1] = {}
for int2 in xrange(1000):
x[ int1 ][int2] = 'asd'
indexes.append((int1, int2))
''', number = 100)
Results:
36.8627537348
12.2223380257
This is a very substantial difference in my opinion.