Why dict.get(key) instead of dict[key]?(为什么 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(无论你选择什么),而
returns default_value (whatever you choose it to be), whereas
dictionary["bogus"]
会引发 KeyError.
如果省略,default_value 为 None,这样
If omitted, default_value is None, such that
dictionary.get("bogus")  # <-- No default specified -- defaults to None
返回 None 就像 
dictionary.get("bogus", None)
会的.
这篇关于为什么 dict.get(key) 而不是 dict[key]?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:为什么 dict.get(key) 而不是 dict[key]?
				
        
 
            
        - 如何在 Python 的元组列表中对每个元组中的第一个值求和? 2022-01-01
 - pytorch 中的自适应池是如何工作的? 2022-07-12
 - 沿轴计算直方图 2022-01-01
 - 分析异常:路径不存在:dbfs:/databricks/python/lib/python3.7/site-packages/sampleFolder/data; 2022-01-01
 - 如何将一个类的函数分成多个文件? 2022-01-01
 - 如何在 python3 中将 OrderedDict 转换为常规字典 2022-01-01
 - python check_output 失败,退出状态为 1,但 Popen 适用于相同的命令 2022-01-01
 - 使用Heroku上托管的Selenium登录Instagram时,找不到元素';用户名'; 2022-01-01
 - padding='same' 转换为 PyTorch padding=# 2022-01-01
 - python-m http.server 443--使用SSL? 2022-01-01
 
				
				
				
				