为什么使用dict.get(key)而不是dict [key]? [英] Why dict.get(key) instead of dict[key]?

查看:127
本文介绍了为什么使用dict.get(key)而不是dict [key]?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

今天,我遇到了一个 dict 方法 get 值。

Today, I came across the dict method get which, given a key in the dictionary, returns the associated value.

此功能有什么用途?如果我想找到与字典中的键相关联的值,我可以直接执行 dict [key] ,并返回相同的事情:

For what purpose is this function useful? If I wanted to find a value associated with a key in a dictionary, I can just do dict[key], and it returns the same thing:

dictionary = {"Name": "Harry", "Age": 17}
dictionary["Name"]
dictionary.get("Name")


推荐答案

如果密钥缺失,请提供默认值:

It allows you to provide a default value if the key is missing:

dictionary.get("bogus", default_value)

返回 default_value (无论你选择是什么) p>

returns default_value (whatever you choose it to be), whereas

dictionary["bogus"]

将提出一个 KeyError

如果省略, default_value ,这样

dictionary.get("bogus")  # <-- No default specified -- defaults to None

返回就像

dictionary.get("bogus", None)

会。

这篇关于为什么使用dict.get(key)而不是dict [key]?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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