How to test if one dict is subset of another?
Paul Rubin
http
Tue Feb 20 14:54:07 EST 2007
"Jay Tee" <jeff.templon at gmail.com> writes:
> Python 2.2.3 (#1, Oct 26 2003, 11:49:53)
> ImportError: No module named sets
Hmm, well I think the sets module in 2.3 is written in Python, so you
could drop it into your application for use in 2.2. Better would be
to use the C version from 2.4 if you can. Or you could fake it with
dicts. Sets are really just dicts under the skin. Instead of
set([1,2,3]) you'd use {1:True, 2:True, 3:True}. To intersect
two of them (untested):
def intersection(d1,d2):
if len(d2) < len(d1):
# swap them so d1 is the smaller one
d1,d2 = d2,d1
r = {}
for k in d1.iterkeys():
if k in d2:
r[k] = True
return r
The d1,d2 swap is just an optimization, since access is constant-time
you want to scan the smaller dictionary to minimize the number of
lookups.
More information about the Python-list
mailing list