【发布时间】:2018-02-06 17:53:35
【问题描述】:
无法将不可散列的对象插入到字典中。它已记录在案,这是有充分理由的。
但是,我不明白为什么它会影响会员资格测试:
if value not in somedict:
print("not present")
我假设成员资格测试只能返回 True 或 False。但是当value 不可散列时,它会以TypeError: unhashable type 失败。我想说True 应该是这个not in 测试的正确答案,因为value 显然不包含在somedict 中,并且它不能插入是完全不相关的。
另一个例子:
try:
result = somedict[value]
except KeyError:
# handle the missing key
当该值不可散列时,它会以TypeError: unhashable type 失败,我希望改为KeyError。
还有:
somedict.get(value, default)
不返回默认值,而是抛出TypeError。
那么为什么unhashable in somedict 不评估为False 以及只返回True 或False 的正确测试是什么?
更新:
object.__contains__(self, item)调用以实现成员资格测试运算符。如果 item 在 self 中,则返回 true,否则返回 false。
(来自“数据模型 - Python 文档”)
附录:
这是用户界面程序的简化部分,当其中一个参数是 dict 时失败。
# args = list of function arguments created from user's input
# where "V1" stands for value1 and "V2" stands for value2
XLAT = {'V1': value1, 'V2': value2}
args = [XLAT.get(a, a) for a in args]
function(*args)
【问题讨论】:
标签: python dictionary