Python dictionary get() 方法用于检索与指定 key 对应的值。
此方法接受键和值,其中 value 是可选的。如果在字典中找不到键,但指定了值,则此方法将检索指定的值。另一方面,如果在字典中找不到键并且也没有指定值,则此方法检索 None。
使用字典时,通常的做法是在字典中检索指定键的值。例如,如果您经营一家书店,您可能希望了解您收到了多少图书订单。
语法
以下是 Python dictionary get() 方法的语法 -
dict.get(key, value)
参数
此方法接受两个参数,如下所示:
- key − 这是要在字典中搜索的 Key。
- value (可选) − 这是在指定键不存在时要返回的 Value。它的默认值为 None。
返回值
此方法返回给定键的值。
如果 key 不可用且未给出值,则返回默认值 None。
如果未给出 key 且指定了值,则返回此值。
例如果作为参数传递给 get() 方法的键存在于字典中,则返回其相应的值。
以下示例显示了 Python dictionary get() 方法的用法。这里创建了一个字典 'dict',其中包含键 'Name' 和 'Age'。然后,键 'Age' 作为参数传递给该方法。因此,从字典中检索其相应的值 '7':
# creating the dictionary
dict = {'Name': 'Zebra', 'Age': 7}
# printing the value of the given key
print ("Value : %s" % dict.get('Age'))
当我们运行上述程序时,它会产生以下结果——
例
如果作为参数传递的键在字典中不存在,并且也未指定该值,则此方法返回默认值 None。
在这里,键 'Roll_No' 作为参数传递给 get() 方法。在字典 'dict' 中找不到此键,并且也没有指定该值。因此,使用 dict.get() 方法返回默认值 'None'。
# creating the dictionary
dict = {'Name': 'Rahul', 'Age': 7}
# printing the value of the given key
print ("The value is: ", dict.get('Roll_No'))
以下是上述代码的输出 -
例
如果我们传递一个键及其值作为字典中不存在的参数,那么这个方法会返回指定的值。
在下面的代码中,键 'Education' 和值 'Never' 作为参数传递给 dict.get() 方法。由于在字典 'dict' 中找不到给定的键,因此返回当前值。
# creating the dictionary
dict = {'Name': 'Zebra', 'Age': 7}
res = dict.get('Education', "Never")
print ("Value : %s" % res)
在执行上述代码时,我们得到以下输出 -
例
在下面给出的示例中,创建了一个嵌套字典 'dict_1' 。然后使用嵌套的 get() 方法返回给定键的值。
dict_1 = {'Universe' : {'Planet' : 'Earth'}}
print("The dictionary is: ", dict_1)
# using nested get() method
result = dict_1.get('Universe', {}).get('Planet')
print("The nested value obtained is: ", result)
上述代码的输出如下 -
The nested value obtained is: Earth