学习Python中的 dict.get()方法

530 阅读2分钟

摘要:当使用Python字典时,在某些情况下,你可能想访问某个项目的特定值,这时,dict.get() 方法就派上用场了。

定义:Python 的dict.get() 方法希望有一个 key 参数。如果指定的 key 在dictionary 中,该方法将输出与该 key 相关的值。

dict.get() 方法的语法

dict.get() 的方法声明:

dict.get(key, optional_value)

dict.get() 的两个参数 :

  • dict.get() 方法在 dictionary 中搜索的key
  • 可选的值optional_value 是输出的值,如果在字典中找不到键,如果没有指定optional_value ,值就默认为None

dict.get() 的输出值:

如果键在字典中,dict.get() 方法返回指定键的相关值,否则,默认值None 或作为参数传递给字典的optional_value 被返回。

dict.get()方法的基本例子

grades_dict = {'programming': 83, 'math': 85, 'science': 80}
print(grades_dict.get('programming'))
# 83

访问嵌套的字典键值

下面是你如何不小心定义一个有三个相同键的 dictionary。

 
employee_dict = {'id_1': {'name': 'bob', 'age': 20, 'profession': 'programmer'},
                 'id_2': {'name': 'tammy', 'age': 25, 'profession': 'engineer'},
                 'id_3': {'name': 'dylan', 'age': 30, 'profession': 'nurse'}}

print(employee_dict)

输出

{'id_1': {'name': 'bob', 'age': 20, 'profession': 'programmer'}, 
 'id_2': {'name': 'tammy', 'age': 25, 'profession': 'engineer'}, 
 'id_3': {'name': 'dylan', 'age': 30, 'profession': 'nurse'}}

这个代码片段声明了一个普通的 dictionary 以及三个嵌套的 dictionary,然后每个 dictionary 都可以通过其相应的键来访问。

 
# How to access the elements of a nested dictionary:
# list employee names:


id1_employee = employee_dict.get('id_1', {}).get('name')
id2_employee = employee_dict.get('id_2', {}).get('name')
id3_employee = employee_dict.get('id_3', {}).get('name')


print(id1_employee)
# bob

print(id2_employee)
# tammy

print(id3_employee)
# dylan

访问字典元素时 dict.get() 和 dict[key] 的区别

# Empty Dictionary Example
empty_dict = {}


# Applying dict.get() method to an empty dictionary:
print(empty_dict.get('key'))
# None

现在,让我们尝试用标准的方括号方法从一个空的 dictionary 中获取一个键来索引一个不存在的键。

# Applying dict[] to an empty dictionary.
# This results in a keyError being returned:
print(empty_dict['key'])

这导致了下面的错误信息,用dict.get() 就可以避免。

Traceback (most recent call last):
  File "C:\Users\xcent\Desktop\code.py", line 11, in <module>
    print(empty_dict['key'])
KeyError: 'key'