Using Dictionaries in Sets - dict objects are unhashable?

Ben Cartwright bencvt at gmail.com
Wed Mar 22 02:30:47 CET 2006


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




More information about the Python-list mailing list