python - 字典键 : custom objects vs lists

标签 python list dictionary

我读到列表不能是字典键,因为可变对象不能被散列。 但是,自定义对象似乎也是可变的:

# custom object
class Vertex(object):
    def __init__(self, key):
        self.key = key

v = Vertex(1)
v.color = 'grey' # this line suggests the custom object is mutable

但是,与列表不同的是,它们可以用作字典键;为什么是这样?在这两种情况下,我们不能简单地散列某种 id(例如对象在内存中的地址)吗?

最佳答案

Why Lists can't be Dictionary Keys 中所述:

Lists as Dictionary Keys

That said, the simple answer to why lists cannot be used as dictionary keys is that lists do not provide a valid hash method. Of course, the obvious question is, "Why not?"

Consider what kinds of hash functions could be provided for lists.

If lists hashed by id, this would certainly be valid given Python's definition of a hash function -- lists with different hash values would have different ids. But lists are containers, and most other operations on them deal with them as such. So hashing lists by their id instead would produce unexpected behavior such as:

  1. Looking up different lists with the same contents would produce different results, even though comparing lists with the same contents would indicate them as equivalent.

  2. Using a list literal in a dictionary lookup would be pointless -- it would always produce a KeyError.

User Defined Types as Dictionary Keys

What about instances of user defined types?

By default, all user defined types are usable as dictionary keys with hash(object) defaulting to id(object), and cmp(object1, object2) defaulting to cmp(id(object1), id(object2)). This same suggestion was discussed above for lists and found unsatisfactory. Why are user defined types different?

  1. In the cases where an object must be placed in a mapping, object identity is often much more important than object contents.

  2. In the cases where object content really is important, the default settings can be redefined by overridding __hash__ and __cmp__ or __eq__.

Note that it is often better practice, when an object is to be associated with a value, to simply assign that value as one of the object's attributes.

关于python - 字典键 : custom objects vs lists,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41405174/

相关文章:

python - 将 Dataframe.describe 输出转换为某些 json

python - 从字符串**正确地**创建一个 lambda 函数

python - 将多个元素(基于条件)移动到列表末尾

python:避免列表的zip截断

python - 如何在 tensorflow 中的切片张量上使用 tf.clip_by_value()?

Python 字符串查找

python - 为什么这两种计算总和的方法会产生不同的运行时间

c# - 在 C# 中将数组添加到字典

python - 如何设置可选参数?

python - 在 python 中转置(旋转)列表字典