How do I check that multiple keys are in a dict in a single pass? How do I check that multiple keys are in a dict in a single pass? python python

How do I check that multiple keys are in a dict in a single pass?


Well, you could do this:

>>> if all (k in foo for k in ("foo","bar")):...     print "They're there!"...They're there!


if {"foo", "bar"} <= myDict.keys(): ...

If you're still on Python 2, you can do

if {"foo", "bar"} <= myDict.viewkeys(): ...

If you're still on a really old Python <= 2.6, you can call set on the dict, but it'll iterate over the whole dict to build the set, and that's slow:

if set(("foo", "bar")) <= set(myDict): ...


Simple benchmarking rig for 3 of the alternatives.

Put in your own values for D and Q

>>> from timeit import Timer>>> setup='''from random import randint as R;d=dict((str(R(0,1000000)),R(0,1000000)) for i in range(D));q=dict((str(R(0,1000000)),R(0,1000000)) for i in range(Q));print("looking for %s items in %s"%(len(q),len(d)))'''>>> Timer('set(q) <= set(d)','D=1000000;Q=100;'+setup).timeit(1)looking for 100 items in 6324990.28672504425048828#This one only works for Python3>>> Timer('set(q) <= d.keys()','D=1000000;Q=100;'+setup).timeit(1)looking for 100 items in 6320842.5987625122070312e-05>>> Timer('all(k in d for k in q)','D=1000000;Q=100;'+setup).timeit(1)looking for 100 items in 6322191.1920928955078125e-05