python中字典的键必须是不可变的吗_不可变字典,仅用作另一个字典的键

我需要实现一个可散列的dict,这样我就可以使用一个字典作为另一个字典的键。

不过,我收到一位同事的通知,他说:“这并不是一成不变的,因此不安全。”。你可以用它,但它确实让我感觉像只悲伤的熊猫。

所以我开始四处寻找创造一个不变的。我不需要将“键dict”与另一个“键dict”进行比较。它的唯一用途是作为另一本字典的钥匙。

我想到了以下几点:class HashableDict(dict):

"""Hashable dict that can be used as a key in other dictionaries"""

def __new__(self, *args, **kwargs):

# create a new local dict, that will be used by the HashableDictBase closure class

immutableDict = dict(*args, **kwargs)

class HashableDictBase(object):

"""Hashable dict that can be used as a key in other dictionaries. This is now immutable"""

def __key(self):

"""Return a tuple of the current keys"""

return tuple((k, immutableDict[k]) for k in sorted(immutableDict))

def __hash__(self):

"""Return a hash of __key"""

return hash(self.__key())

def __eq__(self, other):

"""Compare two __keys"""

return self.__key() == other.__key() # pylint: disable-msg=W0212

def __repr__(self):

"""@see: dict.__repr__"""

return immutableDict.__repr__()

def __str__(self):

"""@see: dict.__str__"""

return immutableDict.__str__()

def __setattr__(self, *args):

raise TypeError("can't modify immutable instance")

__delattr__ = __setattr__

return HashableDictBase()

我使用了以下内容来测试功能:d = {"a" : 1}

a = HashableDict(d)

b = HashableDict({"b" : 2})

print a

d["b"] = 2

print a

c = HashableDict({"a" : 1})

test = {a : "value with a dict as key (key a)",

b : "value with a dict as key (key b)"}

print test[a]

print test[b]

print test[c]

它给出:{'a': 1}

{'a': 1}

value with a dict as key (key a)

value with a dict as key (key b)

value with a dict as key (key a)

作为输出

这是“最好的可能”不变的字典,我可以使用,以满足我的要求?如果没有,还有什么更好的解决办法?

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值