从
Python Library Docs
d[key]
Return the item of d with key key. Raises a KeyError if key is not in the map.
If a subclass of dict defines a method __missing__(), if the key key is not present, the d[key] operation calls that method with the key key as argument. The d[key] operation then returns or raises whatever is returned or raised by the __missing__(key) call if the key is not present. No other operations or methods invoke __missing__(). If __missing__() is not defined, KeyError is raised. __missing__() must be a method; it cannot be an instance variable. […]
和
get(key[, default])
Return the value for key if key is in the dictionary, else default. If default is not given, it defaults to None, so that this method never raises a KeyError.
差异在于返回值.当您要求与不存在的键对应的值时,您要求
>提出了一个KeyError
>调用回调
>返回一个默认值
Python通过多种方法提供了不同的功能.
在没有找到密钥的情况下,使用[],或者在调用_missing_或引发异常时,会出现性能问题.关键IS存在时哪一个更快,我检查了源代码. (我使用2.7.2进行此检查.)在dictobject.c中,我们看到:
>调用dict_get
> []调用dict_subscript
现在如果值存在,在dict_get我们有
if (!PyArg_UnpackTuple(args, "get", 1, 2, &key, &failobj))
return NULL;
if (!PyString_CheckExact(key) ||
(hash = ((PyStringObject *) key)->ob_shash) == -1) {
hash = PyObject_Hash(key);
if (hash == -1)
return NULL;
}
ep = (mp->ma_lookup)(mp, key, hash);
在dict_subscript我们有
assert(mp->ma_table != NULL);
if (!PyString_CheckExact(key) ||
(hash = ((PyStringObject *) key)->ob_shash) == -1) {
hash = PyObject_Hash(key);
if (hash == -1)
return NULL;
ep = (mp->ma_lookup)(mp, key, hash);
唯一的区别是get做一个额外的解包元组!
重大?我不知道. 🙂