在本教程中,我们将借助示例了解 Python Dictionary get() 方法。
如果键在字典中,get() 方法返回指定键的值。
示例
marks = {'Physics':67, 'Maths':87}
print(marks.get('Physics'))
# Output: 67
用法:
用法:
dict.get(key[, value])
参数:
get() 方法最多接受两个参数:
- key- 要在字典中搜索的键
- value(可选) - 返回的值,如果
key没有找到。默认值为None.
返回:
get() 方法返回:
- 如果
key在字典中,则指定key的值。 None如果未找到key且未指定value。value如果找不到key并且指定了value。
示例 1:get() 如何用于字典?
person = {'name': 'Phill', 'age': 22}
print('Name: ', person.get('name'))
print('Age: ', person.get('age'))
# value is not provided
print('Salary: ', person.get('salary'))
# value is provided
print('Salary: ', person.get('salary', 0.0))
输出
Name: Phill Age: 22 Salary: None Salary: 0.0
Python get() 方法与 dict[key] 访问元素
如果缺少 key,get() 方法将返回默认值。
但是,如果在使用 dict[key] , KeyError 时未找到 key,则会引发异常。
person = {}
# Using get() results in None
print('Salary: ', person.get('salary'))
# Using [] results in KeyError
print(person['salary'])
输出
Salary: None
Traceback (most recent call last):
File "", line 7, in
print(person['salary'])
KeyError: 'salary' 相关用法
- Python Dictionary clear()用法及代码示例
- Python Dictionary update()用法及代码示例
- Python Dictionary setdefault()用法及代码示例
- Python Dictionary pop()用法及代码示例
- Python Dictionary popitem()用法及代码示例
- Python Dictionary has_key()用法及代码示例
- Python Dictionary items()用法及代码示例
- Python Dictionary copy()用法及代码示例
- Python Dictionary keys()用法及代码示例
- Python Dictionary values()用法及代码示例
- Python Dictionary fromkeys()用法及代码示例
- Python Decimal shift()用法及代码示例
- Python Decimal next_plus()用法及代码示例
- Python Decimal rotate()用法及代码示例
- Python Decimal max_mag()用法及代码示例
- Python Datetime.replace()用法及代码示例
- Python DateTime转integer用法及代码示例
- Python Decimal as_integer_ratio()用法及代码示例
- Python Decimal is_subnormal()用法及代码示例
- Python DataFrame.to_excel()用法及代码示例
注:本文由纯净天空筛选整理自 Python Dictionary get()。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。
