hashing an array - howto

Robert Kern robert.kern at gmail.com
Mon Sep 8 22:53:02 CEST 2008


bearophileHUGS at lycos.com wrote:
> John Machin:
>> Consider this:>>> hash(123) == hash(123.0) == hash(123L)
>> True
> 
> Right... Can you explain me why Python designers have chosen to build
> a hash() like that?

Because that's the kind of hash that dicts expect. If two objects are equal 
(i.e. (x==y) is True), they need to have their hash values equal as well. In 
order to do a lookup into a dict, it will hash the key and search the table for 
a that hash value. If there are multiple keys with the same hash value, then the 
dict will compare the keys by value to find a match. Since (123==123.0==123L), 
they must also have the same hash value such that

   {123.0: 'got it'}[123] == 'got it'

-- 
Robert Kern

"I have come to believe that the whole world is an enigma, a harmless enigma
  that is made terrible by our own mad attempt to interpret it as though it had
  an underlying truth."
   -- Umberto Eco




More information about the Python-list mailing list