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.