Using non-hashable Python objects as keys in dictionaries

后端 未结 8 1582
栀梦
栀梦 2020-12-19 16:00

Python doesn\'t allow non-hashable objects to be used as keys in other dictionaries. As pointed out by Andrey Vlasovskikh, there is a nice workaround for the special case of

8条回答
  •  北荒
    北荒 (楼主)
    2020-12-19 16:13

    If you really must, make your objects hashable. Subclass whatever you want to put in as a key, and provide a __hash__ function which returns an unique key to this object.

    To illustrate:

    >>> ("a",).__hash__()
    986073539
    >>> {'a': 'b'}.__hash__()
    Traceback (most recent call last):
      File "", line 1, in 
    TypeError: 'NoneType' object is not callable
    

    If your hash is not unique enough you will get collisions. May be slow as well.

提交回复
热议问题