Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why 'in' operator with tuple as a key in python so slow?

I have a dict such as:

d=dict()
d[('1','2')] = 'value'

Then I query the key :

if (k1,k2) in d.keys():

When there is million records,the speed is a suffering, any problem with the 'in' operator?

Is it sequential search?

I have to concat str as key to bypass this issue.

like image 900
lbaby Avatar asked Apr 18 '12 08:04

lbaby


1 Answers

You should use

(k1,k2) in d

instead of calling d.keys().

Doing it your way, in Python 2 will result in a linear search and rather negates the benefits of a dict. In Python 3 your code is efficient (see comments below) but my version is clearer.

like image 143
David Heffernan Avatar answered Sep 30 '22 15:09

David Heffernan