小编典典

Python-为什么用dict.get(key)而不是dict [key]?

python

今天,我遇到了该dict方法get,该方法在字典中给定键,然后返回关联的值。

此功能用于什么目的?如果我想找到与字典中的键相关联的值,我可以这样做dict[key],并且它返回相同的内容:

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

阅读 724

收藏
2020-02-08

共1个答案

小编典典

如果密钥丢失,它允许您提供默认值:

dictionary.get("bogus", default_value)

返回default_value(无论您选择的是什么),而

dictionary["bogus"]

会提出一个KeyError

如果省略,default_value则为None,这样

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

返回None就像

dictionary.get("bogus", None)
2020-02-08