Check for mutability in Python?

后端 未结 7 1858
小鲜肉
小鲜肉 2020-12-28 13:23

Consider this code:

a = {...} # a is an dict with arbitrary contents
b = a.copy()
  1. What role does mutability play in the keys and valu
7条回答
  •  不思量自难忘°
    2020-12-28 13:54

    Dicts are unordered sets of key:value pairs. The keys must be immutable, and therefore hashable. To determine if an object is hashable, you can use the hash() function:

    >>> hash(1)
    1
    >>> hash('a')
    12416037344
    >>> hash([1,2,3])
    Traceback (most recent call last):
      File "", line 1, in 
    TypeError: unhashable type: 'list'
    >>> hash((1,2,3))
    2528502973977326415
    >>> hash({1: 1})
    Traceback (most recent call last):
      File "", line 1, in 
    TypeError: unhashable type: 'dict'
    

    The values, on the other hand, can be any object. If you need to check if an object is immutable, then I would use hash().

提交回复
热议问题