objects as keys in python dictionaries

前端 未结 2 1951
[愿得一人]
[愿得一人] 2021-02-01 04:52

I\'m trying to use an object as a key in a python dictionary, but it\'s behaving in a way that I can\'t quite understand.

First I create a dictionary with my object as t

2条回答
  •  孤街浪徒
    2021-02-01 05:32

    Since dicts are hash tables under the hood, you need to define both __eq__ and __hash__ for that to work.

    The basic rule of thumb is:

    • For objects that __eq__ compares equal, __hash__ must return the same hash.

    From your description, something like

    def __hash__(self):
        return hash(str(self))
    

    should work.

提交回复
热议问题