python怎么设置字典_在字典Python中设置索引

您只能对字典键使用不可变的值。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])})

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值