# Most efficient solution?

phawkins at connact.com phawkins at connact.com
Fri Jul 20 16:06:01 EDT 2001

```>>>>> "TR" == Terry Reedy <tjreedy at home.com> writes:

>> C = {}
>> for item in B:
>> C[item]=None

TR> This sort of makes me wish we had dict comprehensions to match list
TR> comprehensions:

TR> C = {item:None for item in B}
TR> or
TR> C = {item:1  for item in B}
TR> as revised and then discarded

So what's wrong with list comprehensions?  Observe, grasshopper:

Python 2.0 (#8, Oct 16 2000, 17:27:58) [MSC 32 bit (Intel)] on win32

import time

a = [str(i) for i in range(7500)]
b = [str(i) for i in range(0, 7500 * 5, 5)]
c = {}

for item in b:
c[item] = 1

def dict(a,c):
start = time.clock()
for item in a:
d = filter(c.has_key, a)
stend = time.clock()
print "get: %6.2f"%(stend-start)

def comp(a,b):
start = time.clock()
out = [i for i in a if i not in b]
stend = time.clock()
print "get: %6.2f"%(stend-start)

>>> >>> >>> ... ... >>> ... ... ... ... ... ... >>> ... ... ... ... ... >>> ... ... ... ... ... ... ... >>> >>>
>>>
>>>
>>> comp(a,b)
get:  19.78
>>> dict(a,c)
get: 154.77
>>>
--
Patricia J. Hawkins
Hawkins Internet Applications, LLC

```