首页 > 文章列表 > python使用get()访问字典值

python使用get()访问字典值

Python get
478 2022-08-07

1、一般访问字典中的键值作为索引引用值,但会出现问题。如果访问的键值不在字典中,就会出错。

2、可以通过get()访问键值对,当键值对不存在时,将返回默认值,可以指定这个默认值。

实例

age = {
    'Tom': 18,
    'Jerry': 12,
    'Bob': 23
}
print(age.get('Ann', 'not found!'))  # 指定第二个参数作为返回的默认值
print(age.get('Lucy'))  # 不指定时,就返回None
# output:
# not found!
# None

本文教程操作环境:windows7系统、Python 3.9.1,DELL G3电脑。