python字典是什么数据结构_Python字典数据结构哪个方法d[]或d.get()?

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_还是引发异常。当键存在时,哪一个速度更快,我检查了源代码。(我用了2.7.2来做这个检查。)在dictobject.c中我们看到:get调用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执行额外的解包元组!

重要吗?我不知道。:-)

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值