Why doesn't Python hash lists using ID?

后端 未结 3 412
滥情空心
滥情空心 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

    The reason is right here (Why must dictionary keys be immutable)

    Some unacceptable solutions that have been proposed:

    • Hash lists by their address (object ID). This doesn’t work because if you construct a new list with the same value it won’t be found; e.g.:

      mydict = {[1, 2]: '12'}

      print mydict[[1, 2]]

    would raise a KeyError exception because the id of the [1, 2] used in the second line differs from that in the first line. In other words, dictionary keys should be compared using ==, not using is.

提交回复
热议问题