How do you use the get function in Python?
In Python, it is common to use the get method to retrieve the value of a specified key in a dictionary. The get method takes two parameters: the key and a default value. If the key is found in the dictionary, it returns the corresponding value; if the key is not found, it returns the default value.
Here is an example:
# 创建一个字典
person = {'name': 'Alice', 'age': 25, 'gender': 'female'}
# 使用get函数获取键的值
name = person.get('name')
print(name) # 输出: Alice
age = person.get('age')
print(age) # 输出: 25
# 使用get函数获取不存在的键的值
city = person.get('city', 'unknown')
print(city) # 输出: unknown,因为键'city'不存在于字典中
# 可以省略默认值参数,默认值为None
gender = person.get('gender')
print(gender) # 输出: female
# 可以使用get函数来安全地获取嵌套字典中的值
person = {'name': 'Bob', 'address': {'street': '123 Main St', 'city': 'New York'}}
street = person.get('address').get('street')
print(street) # 输出: 123 Main St
By using the get method, we can prevent KeyErrors from being raised due to keys not existing. Additionally, we can specify a default value to be returned when a key doesn’t exist.