Hash - Python dictionary keyswhich are class objects comparison with multiple comparer

De openkb
Aller à : Navigation, rechercher

Sommaire

Questions

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=name
        self.city=city

    def __eq__(self,other):
        hash_equality= (self.name==other.name)
        if(not hash_equality):
            #check with lower
            return (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.

Answers

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.name


def func(d):
    d_copy = dict((WrapKey(key), value) for key, value in d.iteritems())
    # d_copy will now ignore case

Source

License : cc by-sa 3.0

http://stackoverflow.com/questions/9835668/python-dictionary-keyswhich-are-class-objects-comparison-with-multiple-compare

Related

Outils personnels
Espaces de noms

Variantes
Actions
Navigation
Outils