Python 字典 get() 方法



Python 字典 get() 方法用於檢索與指定鍵對應的值。

此方法接受鍵和值,其中值是可選的。如果字典中找不到鍵,但指定了值,則此方法將檢索指定的值。另一方面,如果字典中找不到鍵並且也沒有指定值,則此方法將檢索 None。

在使用字典時,通常的做法是檢索字典中指定鍵的值。例如,如果您經營一家書店,您可能希望瞭解您收到了多少本書的訂單。

語法

以下是Python 字典 get() 方法的語法:

dict.get(key, value)

引數

此方法接受如下所示的兩個引數

  • key − 這是要在字典中搜索的鍵。

  • value (optional) − 如果指定的鍵不存在,則返回此值。其預設值為 None。

返回值

此方法返回給定鍵的值。

  • 如果鍵不可用且值也沒有給出,則它返回預設值 None。

  • 如果未給出鍵但指定了值,則它返回此值。

示例

如果作為引數傳遞給 get() 方法的鍵存在於字典中,則它將返回其對應的值。

以下示例顯示了 Python 字典 get() 方法的用法。這裡建立了一個包含鍵:“Name”和“Age”的字典 'dict'。然後,將鍵 'Age' 作為引數傳遞給該方法。因此,其對應的值 '7' 從字典中檢索。

# creating the dictionary
dict = {'Name': 'Zebra', 'Age': 7}
# printing the value of the given key
print ("Value : %s" %  dict.get('Age'))

執行上述程式時,它會產生以下結果:

Value : 7

示例

如果作為引數傳遞的鍵不存在於字典中,並且也沒有指定值,則此方法將返回預設值 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'))

以下是上述程式碼的輸出:

The value is:  None

示例

如果我們傳遞一個鍵及其值作為引數,而該鍵不存在於字典中,則此方法將返回指定的值。

在下面的程式碼中,鍵 'Education' 和值 'Never' 作為引數傳遞給 dict.get() 方法。由於在字典 'dict' 中找不到給定的鍵,因此返回當前值。

# creating the dictionary
dict = {'Name': 'Zebra', 'Age': 7}
res = dict.get('Education', "Never")
print ("Value : %s" % res)

執行上述程式碼時,我們將得到以下輸出:

Value : Never

示例

在下面給出的示例中,建立了一個巢狀字典 '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 dictionary is: {'Universe': {'Planet': 'Earth'}}
The nested value obtained is: Earth
python_dictionary.htm
廣告