Python dict.get('key')与dict ['key'] [英] Python dict.get('key') versus dict['key']

查看:83
本文介绍了Python dict.get('key')与dict ['key']的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么会引发KeyError:

Why does this throw a KeyError:

d = dict()
d['xyz']

但这不是吗?

d = dict()
d.get('xyz')

我也很好奇描述符是否在这里发挥作用.

I'm also curious if descriptors play a role here.

推荐答案

这只是定义 get()方法的方式.

This is simply how the get() method is defined.

来自 Python文档:

如果key在字典中,则返回key的值,否则返回默认值.如果未指定default,则默认为None,因此此方法永远不会引发KeyError.

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.

默认的未找到"返回值为 None .您可以返回任何其他默认值.

The default "not-found" return value is None. You can return any other default value.

d = dict()
d.get('xyz', 42)  # returns 42

这篇关于Python dict.get('key')与dict ['key']的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆