Monday, November 21, 2016

first hash past the post

Numeric types in Python have the interesting property that their hash() is often their value:

>>> hash(1)
1
>>> hash(1.0)
1

Python also considers floating point and integers of the same value to be equal:

>>> 1 == 1.0
True

Two things with the same hash that are equal count as the same key in a dict:

>>> 1 in {1.0: 'cat'}
True

However, it is possible for the key to be either an int or a float:

>>> {1: 'first'}
{1: 'first'}
>>> {1.0: 'second'}
{1.0: 'second'}

Whichever key is used first sticks.  Later writes to the dict can change the value, but the int or float key remains:

>>> {1: 'first', 1.0: 'second'}
{1: 'second'}
>>> {1.0: 'first', 1: 'second'}
{1.0: 'second'}

3 comments:

  1. This also works with booleans.

    d = dict()
    d[True] = 1
    d[1] = 2

    d → {True: 2}

    ReplyDelete
  2. Nice and very helpful information i have got from your post : usefull site

    ReplyDelete