Python dictionary keys(which are class objects) comparison with multiple comparer

2024/10/7 20:28:24

I am using custom objects as keys in python dictionary. These objects has some default hash and eq methods defined which are being used in default comparison But in some function i need to use a different way to compare these objects. So is there any way to override or pass a new comparer for these key comparison for this specific function only.

Updated: My class has following type of functionality ( here i can not edit hash method ,it will affect a lot at other places)

class test(object):def __init__(self,name,city):self.name=nameself.city=citydef __eq__(self,other):hash_equality= (self.name==other.name)if(not hash_equality):#check with lowerreturn (self.name.lower()==other.name.lower())def  __hash__(self):return self.name.__hash__()my_dict={}
a=test("a","city1")
my_dict[a]="obj1"
b=test("a","city2")
print b in my_dict  #prints true
c=test("A","city1")
print c in my_dict  #prints false
print c in my_dict.keys() #prints true
# my_dict[c]   throw error

This is the normal functionality. But in one specific method i want to override/or pass a new custom comparer where the new hash code is like

def  __hash__(self):return self.name.lower().__hash__()

so that c in my_dict returns ture

or my_dict[c] will return "obj1"

Sorry for so many updates.

Like in sorting we can pass custom method as comparer , is there any way to do the same here.

Answer

The only way to make this work is to create a copy of your dictionary using the new hash and comparison-function. The reason is that the dictionary needs to rehash every stored key with the new hash-function to make the lookup work as you desire. Since you cannot provide a custom hash-function to a dictionary (it always uses the one of the key-objects), your best bet is probably to wrap your objects in a type that uses your custom hash and comparison-functions.

class WrapKey(object):__init__(self, wrapee):self._wrapee = wrapee__hash__(self):return self._wrapee.name.lower().__hash__()__eq__(self, other):return self._wrapee.name == other._wrapee.namedef func(d):d_copy = dict((WrapKey(key), value) for key, value in d.iteritems())# d_copy will now ignore case
https://en.xdnf.cn/q/70202.html

Related Q&A

How can I make np.save work for an ndarray subclass?

I want to be able to save my array subclass to a npy file, and recover the result later.Something like:>>> class MyArray(np.ndarray): pass >>> data = MyArray(np.arange(10)) >>&g…

With ResNet50 the validation accuracy and loss is not changing

I am trying to do image recognition with ResNet50 in Python (keras). I tried to do the same task with VGG16, and I got some results like these (which seem okay to me): resultsVGG16 . The training and v…

string has incorrect type (expected str, got spacy.tokens.doc.Doc)

I have a dataframe:train_review = train[review] train_reviewIt looks like:0 With all this stuff going down at the moment w... 1 \The Classic War of the Worlds\" by Timothy Hi... 2 T…

custom URLs using django rest framework

I am trying to use the django rest framework to expose my models as APIs.serializersclass UserSerializer(serializers.HyperlinkedModelSerializer):class Meta:model = Userviewsetclass UserViewSet(viewsets…

Does python logging.FileHandler use block buffering by default?

The logging handler classes have a flush() method. And looking at the code, logging.FileHandler does not pass a specific buffering mode when calling open(). Therefore when you write to a log file, it …

Non brute force solution to Project Euler problem 25

Project Euler problem 25:The Fibonacci sequence is defined by the recurrence relation: Fn = Fn−1 + Fn−2, where F1 = 1 and F2 = 1. Hence the first 12 terms will be F1 = 1, F2 = 1, F3 = 2, F4 = 3, F5 =…

python:class attribute/variable inheritance with polymorphism?

In my endeavours as a python-apprentice i got recently stuck at some odd (from my point of view) behaviour if i tried to work with class attributes. Im not complaining, but would appreciate some helpfu…

Unable to load firefox in selenium webdriver in python

I have installed Python 3.6.2, Selenium 3.5.0 with GeckoDriver 0.18.0 and the firefox version is 54.0.1version on windows 7. I am trying to run a selenium script which is loading a firefox where i get …

Plot hyperplane Linear SVM python

I am trying to plot the hyperplane for the model I trained with LinearSVC and sklearn. Note that I am working with natural languages; before fitting the model I extracted features with CountVectorizer …

Calculating plugin dependencies

I have the need to create a plugin system that will have dependency support and Im not sure the best way to account for dependencies. The plugins will all be subclassed from a base class, each with i…