objects as keys in python dictionaries

前端 未结 2 1950
[愿得一人]
[愿得一人] 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:30

    From the python documentation:

    A dictionary’s keys are almost arbitrary values. Values that are not hashable, that is, values containing lists, dictionaries or other mutable types (that are compared by value rather than by object identity) may not be used as keys.

    Hashable is defined as follows

    An object is hashable if it has a hash value which never changes during its lifetime (it needs a __hash__() method), and can be compared to other objects (it needs an __eq__() or __cmp__() method). Hashable objects which compare equal must have the same hash value.

    Hashability makes an object usable as a dictionary key and a set member, because these data structures use the hash value internally.

    So if you want to do this, you need to override the default __hash__() method on your object (see the comment from Steven Rumbalski below for further explanation).


    >>> content_type in package_disseminators.keys()
    True
    

    I suppose this works because dict.keys() returns a list, and __contains__ probably checks for equality, but not for the same hashes.

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题