您只能对字典键使用不可变的值。set()值是可变的,因此不能使用这些值:>>> lst = ['A', 'B', 'C', 'A', 'B']
>>> {{x}: y for x, y in enumerate(lst)}
Traceback (most recent call last):
File "", line 1, in
File "", line 1, in
TypeError: unhashable type: 'set'
演示:>>> lst = ['A', 'B', 'C', 'A', 'B']
>>> {frozenset([x]): y for x, y in enumerate(lst)}
{frozenset([4]): 'B', frozenset([2]): 'C', frozenset([3]): 'A', frozenset([0]): 'A', frozenset([1]): 'B'}
字典键必须是散列的;请参阅映射类型文档:A dictionary’s keys are almost arbitrary values. Values that are not hashable, that is, values containing lists, dictionaries or other mutable types (that are compared by value rather than by object identity) may not be used as keys.An object is hashable if it has a hash value which never changes during its lifetime (it needs a __hash__() method), and can be compared to other objects (it needs an __eq__() or __cmp__() method). Hashable objects which compare equal must have the same hash value.
因为set值是可变的,它们不符合哈希标准;现在比较相等的任何两个集合,可以在以后更改为不再相等,因此它们的哈希值也需要更改。因为字典和集合都依赖于哈希值而不是更改,所以可变容器不能用作字典键。在
Dictionary值(与键相对)不限于散列对象。在
如果要创建set值,请使用循环:dct = {}
for x, y in enumerate(lst):
dct.setdefault(y, set()).add(x)
或者使用^{}对象,并避免.setdefault()调用:from collections import defaultdict
dct = defaultdict(set)
for x, y in enumerate(lst):
dct[y].add(x)
演示:>>> lst = ['A', 'B', 'C', 'A', 'B']
>>> dct = {}
>>> for x, y in enumerate(lst):
... dct.setdefault(y, set()).add(x)
...
>>> dct
{'A': set([0, 3]), 'C': set([2]), 'B': set([1, 4])}
>>> from collections import defaultdict
>>> dct = defaultdict(set)
>>> for x, y in enumerate(lst):
... dct[y].add(x)
...
>>> dct
defaultdict(, {'A': set([0, 3]), 'C': set([2]), 'B': set([1, 4])})