Why doesn't Python hash lists using ID?

后端 未结 3 420
滥情空心
滥情空心 2021-01-02 17:26

When using a dictionary in Python, the following is impossible:

d = {}
d[[1,2,3]] = 4

since \'list\' is an unhashable type. Ho

3条回答
  •  遥遥无期
    2021-01-02 18:06

    In Python dictionaries keys are compared using ==, and the equality operator with lists does an item-by-item equality check so two different lists with the same elements compare equal and they must behave as the same key in a dictionary.

    If you need to keep a dictionary or set of lists by identity instead of equality you can just wrap the list in a user-defined object or, depending on the context, may be you can use a dictionary where elements are stored/retrieve by using id explicitly.

    Note however that keeping the id of an object stored doesn't imply the object will remain alive, that there is no way for going from id to object and that id may be reused over time for objects that have been garbage collected. A solution is to use

    my_dict[id(x)] = [x, value]
    

    instead of

    my_dict[id(x)] = value
    

提交回复
热议问题