Skip to content

Instantly share code, notes, and snippets.

@eagafonov
Last active March 26, 2018 13:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save eagafonov/9020c2e409cca8fea694fcd16a956979 to your computer and use it in GitHub Desktop.
Save eagafonov/9020c2e409cca8fea694fcd16a956979 to your computer and use it in GitHub Desktop.
Dict is not a mystery

https://dbader.org/blog/python-mystery-dict-expression

class One:
    def __eq__(self, other):
        print("[One] Comparing with {} ({})".format(other, type(other)))
        if type(other) is int and other == 1:
            return True
        return False

    def __hash__(self):
        print("[One] hashing the one")
        return 1

    def __repr__(self):
        return "One()"

class NotOne:
    def __eq__(self, other):
        print("[NotOne] Comparing with {} ({})".format(other, type(other)))
        if type(other) is int and other == 1:
            return True
        return False

    def __hash__(self):
        print("[NotOne] hashing the not-one")
        return 2

    def __repr__(self):
        return "NotOne()"

Dict with numerical keys

In [4]: d = {1: "One", 2: "Two"}
In [5]: d[One()]
[One] hashing the one
[One] Comparing with 1 (<class 'int'>)
'One'

In [6]: d[NotOne()]
[NotOne] hashing the not-one
[NotOne] Comparing with 2 (<class 'int'>)
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-19-d55ac5de3331> in <module>()
----> 1 d[NotOne()]

KeyError: NotOne()


Dict with boolean keys

In [7]: d = {True: "The truth is out there"}

In [8]: d[One()]
[One] hashing the one
[One] Comparing with True (<class 'bool'>)
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-25-0e14ef931187> in <module>()
----> 1 d[One()]

KeyError: One()

Yet more fun: hash collisions

In [12]: d = {NotOne(): "There can be only one", 1: "The One", 2: "The ultimate answer"}
[NotOne] hashing the not-one
[NotOne] Comparing with 2 (<class 'int'>)

In [13]: d
[NotOne] Comparing with 2 (<class 'int'>)
[NotOne] hashing the not-one
{1: 'The One', 2: 'The ultimate answer', NotOne(): 'There can be only one'}

In [14]: d[NotOne()]
[NotOne] hasing the not-one
[NotOne] Comparing with NotOne() (<class '__main__.NotOne'>)
[NotOne] Comparing with 2 (<class 'int'>)
[NotOne] Comparing with NotOne() (<class '__main__.NotOne'>)
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-31-d55ac5de3331> in <module>()
----> 1 d[NotOne()]

KeyError: NotOne()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment