473,804 Members | 3,570 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Using Dictionaries in Sets - dict objects are unhashable?

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 "<interacti ve input>", line 1, in ?
TypeError: dict objects are unhashable

(Bonus points: Why does anything have to be "hashed"? Can't it just
check the references?)

Thanks,

--
Gregory Piñero
Chief Innovation Officer
Blended Technologies
(www.blendedtechnologies.com)
Mar 22 '06 #1
3 24364
Welcome to Python, where all types are either static (and thus
hashable) or volatile (and thus not hashable.)

The way hash tables work (which is what powers the set and dict types),
you have to be able to get a number from an instance of the type, with
the following conditions true:

(1) Every equivalent instance (whatever that means to you) will give
you the same number for the type.

(2) You always get the same number for the instance of the type.
(Because things should be equal to themselves.)
If these two things don't hold true, then the hash tables won't work
like you would expect them to. (Imagine punching in the same dict that
has been modified slightly as the key. What do you expect to get back?)

You *could* create a dict that hashes off of its unique id. But the id
isn't really unique because old ids get recycled.

You *could* convert the dict to a tuple of key-value pairs, and then
hash that, but every value in that tuple would have to be hashable.

Instead of storing the dicts in the set, trying storing something else
that is hashable, and invent some way of "rememberin g" which thing
refers to which dict.

Mar 22 '06 #2
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 "<interacti ve 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

Mar 22 '06 #3
Thanks guys. That was informative and helpful. I'm back on track now.

-Greg
On 21 Mar 2006 17:30:47 -0800, Ben Cartwright <be****@gmail.c om> 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 "<interacti ve 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)
Mar 22 '06 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

21
2497
by: Raymond Hettinger | last post by:
I've gotten lots of feedback on the itertools module but have not heard a peep about the new sets module. * Are you overjoyed/outraged by the choice of | and & as set operators (instead of + and *)? * Is the support for sets of sets necessary for your work and, if so, then is the implementation sufficiently powerful?
4
8373
by: Thomas Philips | last post by:
I'm teaching myself python and in the course of playing around with dictionaries, I tried to create the following trivial dictionary {1:'one', 2:'two'} So I entered >>> dict(1='one',2='two') SyntaxError: keyword can't be an expression As this did not work, I tried
210
10573
by: Christoph Zwerschke | last post by:
This is probably a FAQ, but I dare to ask it nevertheless since I haven't found a satisfying answer yet: Why isn't there an "ordered dictionary" class at least in the standard list? Time and again I am missing that feature. Maybe there is something wrong with my programming style, but I rather think it is generally useful. I fully agree with the following posting where somebody complains why so very basic and useful things are not part...
9
1350
by: javuchi | last post by:
I've been searching thru the library documentation, and this is the best code I can produce for this alogorithm: I'd like to return a dictionary which is a copy of 'another' dictionary whoes values are bigger than 'x' and has the keys 'keys': def my_search (another, keys, x): temp = another.fromkeys(keys) return dict( for k in temp.keys() for v in temp.values() if v>=x])
7
7908
by: ProvoWallis | last post by:
I'm still learning python so this might be a crazy question but I thought I would ask anyway. Can anyone tell me if it is possible to join two dictionaries together to create a new dictionary using the keys from the old dictionaries? The keys in the new dictionary would be the keys from the old dictionary one (dict1) and the values in the new dictionary would be the keys from the old dictionary two (dict2). The keys would be joined by...
1
1494
by: François Pinard | last post by:
Hi, people. I noticed today that dictionaries seem to support `==' comparison. (Retrospectively, it is strange that I never needed it before! :-) Yet, before relying on this, I seeked for confirmation in the Python manuals, and did not succeed in finding it. In particular: http://www.python.org/doc/2.3.5/lib/typesmapping.html is silent on the subject. As for:
15
1371
by: pretoriano_2001 | last post by:
Hello: I have next dictionaries: a={'a':0, 'b':1, 'c':2, 'd':3} b={'a':0, 'c':1, 'd':2, 'e':3} I want to put in a new dictionary named c all the keys that are in b and re-sequence the values. The result I want is: c={'a':0, 'c':1, 'd':2} How can I do this with one line of instruction? I attempted the next but the output is not the expected:
3
4082
by: ZMY | last post by:
I am new to Numpy/Pylab, and I am trying to construct a list of dictionaries with arrays as the items, for example: .... ), 2: ''}, {1: array(), 2: ''}, {1: array(), 2: ''}] ), 2: ''}, {1: array(), 2: ''}, {1: array(), 2: ''}] ), 2: 'Jack'}, {1: array(),
13
6040
by: Martin Drautzburg | last post by:
This may be pretty obvious for most of you: When I have an object (an instance of a class "Foo") I can access attributes via dot notation: aFoo.bar however when I have a dictionary aDict = {"bar":"something"}
0
9705
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9576
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10323
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
10074
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9138
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5515
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5647
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4291
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
2983
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.