Python Dictionary get( ) 是一个内置函数,如果字典中存在一个指定的 key,则返回该 key 的值。如果该键不存在,它默认返回 None。
在本教程中,我们将在实例的帮助下学习Python Dictionary get()方法。
字典get()的语法
该方法的语法是**get()**方法的语法是。
dict.get(key,value)
get() 参数
该get()方法需要两个参数。
- key - 你想返回值的项目的键名。
- value (可选)- 如果在字典中找不到该键,将返回的值。如果没有提供,默认为 None。
从字典 get() 返回值
该get()方法返回
- 如果
key在字典中存在,则返回具有指定key的项目的值。 None如果在字典中没有找到 ,并且没有指定value参数。keyvalue如果没有找到key,则返回。
例子 1 - 如何在 Dictionary 中使用 get() 方法
company = {"name": "Microsoft", "location": "Seattle"}
print("Company Name:", company.get("name"))
print("Company Location:", company.get("location"))
# In case of wrong key name without default value
print("Company Headquarters:", company.get("headquarters"))
# In case of wrong key name with default value
print("Company Headquarters:", company.get("headquarters","Not Found"))
输出
Company Name: Microsoft
Company Location: Seattle
Company Headquarters: None
Company Headquarters: Not Found
例 2 - get() 方法和 dict[key] 访问元素的区别
该方法是 get()方法将不会引发任何异常,如果 key 没有找到,它要么返回 None 或一个默认值(如果提供的话)。
另一方面,当我们使用 dict[key] 如果没有找到键,KeyError 异常被引发。
company = {"name": "Microsoft", "location": "Seattle"}
# In case of wrong key name without default value
print("Company Headquarters:", company.get("headquarters"))
# In case of wrong key name with default value
print("Company Headquarters:", company.get("headquarters","Not Found"))
# when used dict[key]
print(company["headquarters"])
输出
Company Headquarters: None
Company Headquarters: Not Found
Traceback (most recent call last):
File "C:\Personal\IJS\Python_Samples\program.py", line 9, in <module>
print(company["headquarters"])
KeyError: 'headquarters'