Python中字典的get()方法

get()方法是标准python库的一部分,用于访问字典中的元素。有时我们可能需要搜索字典中不存在的键。在这种情况下,按索引的访问方法将引发错误并停止程序。但是我们可以使用get()方法并正确地处理程序。

语法

Syntax: dict.get(key[, value])
The value field is optional.

示例

在下面的示例中,我们创建了一个名为customer的字典。它具有地址和距离作为键。我们可以在不使用get函数的情况下打印键,并在使用get函数时看到区别。

customer = {'Address': 'Hawai', 'Distance': 358}
#printing using Index
print(customer["Address"])

#printing using get
print('Address: ', customer.get('Address'))
print('Distance: ', customer.get('Distance'))

# Key is absent in the list
print('Amount: ', customer.get('Amount'))

# A value is provided for a new key
print('Amount: ', customer.get('Amount', 2050.0))

输出结果

运行上面的代码给我们以下结果-

Hawai
Address: Hawai
Distance: 358
Amount: None
Amount: 2050.0

因此,新方法会自动被get方法接受,而我们不能使用索引来完成。