Using Dictionaries in Sets - dict objects are unhashable?

Gregory Piñero gregpinero at gmail.com
Wed Mar 22 09:16:57 EST 2006


Thanks guys.  That was informative and helpful.  I'm back on track now.

-Greg


On 21 Mar 2006 17:30:47 -0800, Ben Cartwright <bencvt at gmail.com> wrote:
> Gregory Piñero wrote:
> > Hey guys,
> >
> > I don't understand why this isn't working for me.  I'd like to be able
> > to do this.  Is there another short alternative to get this
> > intersection?
> >
> > [Dbg]>>> set([{'a':1},{'b':2}]).intersection([{'a':1}])
> > Traceback (most recent call last):
> >   File "<interactive input>", line 1, in ?
> > TypeError: dict objects are unhashable
>
> Assuming you're using Python 2.4+:
>
> >>> d1 = {'a':1, 'b':2, 'c':3, 'd':5}
> >>> d2 = {'a':1, 'c':7, 'e':6}
> >>> dict((k, v) for k, v in d1.iteritems() if k in d2)
> {'a': 1, 'c': 3}
>
> Or if you're comparing key/value pairs instead of just keys:
>
> >>> dict((k, v) for k, v in d1.iteritems() if k in d2 and d2[k]==v)
> {'a': 1}
>
> Finally, if you're on Python 2.3, use these versions (less efficient
> but still functional):
>
> >>> dict([(k, v) for k, v in d1.iteritems() if k in d2])
> {'a': 1, 'c': 3}
> >>> dict([(k, v) for k, v in d1.iteritems() if k in d2 and d2[k]==v])
> {'a': 1}
>
> --Ben
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>


--
Gregory Piñero
Chief Innovation Officer
Blended Technologies
(www.blendedtechnologies.com)



More information about the Python-list mailing list