How to test if one dict is subset of another?

Jay Tee jeff.templon at gmail.com
Tue Feb 20 16:10:11 EST 2007


Hi,

thanks!  the code lift from 2.3 to 2.2 worked (thank Guido et al for
BACKWARDS COMPATIBILITY ;-)) ... unfortunately I was in a hurry to get
the release out since a colleague's cluster was croaking under the
load of the old, non-indexed version.  Your solution is nicer looking
than mine, and leads to a less complex implementation.  Rolling it
into the next release is going to have to wait a few weeks, I hope I
can remember it that long.  Thanks!!

    JT

On Feb 20, 8:54 pm, Paul Rubin <http://phr...@NOSPAM.invalid> wrote:
> "Jay Tee" <jeff.temp... 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