Using object as key in dictionary in Python - Hash function

2024/10/16 2:23:54

I am trying to use an object as the key value to a dictionary in Python. I follow the recommendations from some other posts that we need to implement 2 functions: __hash__ and __eq__

And with that, I am expecting the following to work but it didn't.

class Test:def __init__(self, name):self.name = namedef __hash__(self):return hash(str(self.name))def __eq__(self, other):return str(self.name) == str(other,name)def TestMethod():test_Dict = {}obj = Test('abc')test_Dict[obj] = objprint "%s" %(test_Dict[hash(str('abc'))].name)       # expecting this to print "abc" 

But it is giving me a key error message:

KeyError: 1453079729188098211
Answer

You don't need to redefine hash and eq to use an object as dictionary key.

class Test:def __init__(self, name):self.name = nametest_Dict = {}obj = Test('abc')
test_Dict[obj] = objprint test_Dict[obj].name

This works fine and print abc. As explained by Ignacio Vazquez-Abrams you don't use the hash of the object but the object itself as key to access the dictionary value.


The examples you found like python: my classes as dict keys. how? or Object of custom type as dictionary key redefine hash and eq for specific purpose.

For example consider these two objects obj = Test('abc') and obj2 = Test('abc').

test_Dict[obj] = obj
print test_Dict[obj2].name

This will throw a KeyError exception because obj and obj2 are not the same object.

class Test:def __init__(self, name):self.name = namedef __hash__(self):return hash(str(self.name))def __eq__(self, other):return str(self.name) == str(other.name)obj = Test('abc')
obj2 = Test('abc')       test_Dict[obj] = obj
print test_Dict[obj2].name

This print abc. obj and obj2 are still different objects but now they have the same hash and are evaluated as equals when compared.

https://en.xdnf.cn/q/69213.html

Related Q&A

Compressing request body with python-requests?

(This question is not about transparent decompression of gzip-encoded responses from a web server; I know that requests handles that automatically.)ProblemIm trying to POST a file to a RESTful web serv…

pyspark row number dataframe

I have a dataframe, with columns time,a,b,c,d,val. I would like to create a dataframe, with additional column, that will contain the row number of the row, within each group, where a,b,c,d is a group k…

Python mysql-connector hangs indefinitely when connecting to remote mysql via SSH

I am Testing out connection to mysql server with python. I need to ssh into the server and establish a mysql connection. The following code works: from sshtunnel import SSHTunnelForwarder import pymysq…

Smooth the edges of binary images (Face) using Python and Open CV

I am looking for a perfect way to smooth edges of binary images. The problem is the binary image appears to be a staircase like borders which is very unpleasing for my further masking process. I am att…

Is there some way to save best model only with tensorflow.estimator.train_and_evaluate()?

I try retrain TF Object Detection API model from checkpoint with already .config file for training pipeline with tf.estimator.train_and_evaluate() method like in models/research/object_detection/model_…

Matching words with NLTKs chunk parser

NLTKs chunk parsers regular expressions can match POS tags, but can they also match specific words? So, suppose I want to chunk any structure with a noun followed by the verb "left" (call th…

How to create a dual-authentication HTTPS client in Python without (L)GPL libs?

Both the client and the server are internal, each has a certificate signed by the internal CA and the CA certificate. I need the client to authenticate the servers certificate against the CA certificat…

Generate a certificate for .exe created by pyinstaller

I wrote a script for my company that randomly selects employees for random drug tests. It works wonderfully, except when I gave it to the person who would use the program. She clicked on it and a messa…

Some doubts modelling some features for the libsvm/scikit-learn library in python

I have scraped a lot of ebay titles like this one:Apple iPhone 5 White 16GB Dual-Coreand I have manually tagged all of them in this wayB M C S NAwhere B=Brand (Apple) M=Model (iPhone 5) C=Color (White)…

Python ReportLab use of splitfirst/splitlast

Im trying to use Python with ReportLab 2.2 to create a PDF report. According to the user guide,Special TableStyle Indeces [sic]In any style command the first row index may be set to one of the special …