如何從Python字典中獲取給定鍵的值?


在這篇文章中,我們將向您展示如何從Python中的字典獲取給定鍵的值。以下是完成此任務的四種不同方法:

  • 使用字典索引

  • 使用dict.get()方法

  • 使用keys()函式

  • 使用items()函式

假設我們已經獲取了一個包含鍵值對的字典。我們將從給定的輸入字典中返回給定鍵的值。

方法1:使用字典索引

Python中,我們可以使用dict[key]從字典中檢索值。

演算法(步驟)

以下是執行所需任務的演算法/步驟:

  • 建立一個變數來儲存輸入字典

  • 透過在[]括號中將鍵值傳遞給輸入字典,從輸入字典中獲取給定鍵的值。

  • 列印給定鍵的結果值。

示例1

以下程式使用dict[key]方法返回從輸入字典中給定鍵的值的索引:

# input dictionary demoDictionary = {10: 'TutorialsPoint', 12: 'Python', 14: 'Codes'} # Printing the value of key 10 from a dictionary print("The value of key 10 from dictionary is =", demoDictionary[10])

輸出

The value of key 10 from dictionary is = TutorialsPoint

如果給定的輸入字典中不存在鍵,則會引發KeyError

示例2

在下面的程式碼中,鍵'hello'不在輸入列表中。因此,當我們嘗試列印鍵'hello'的值時,會返回KeyError

# input dictionary demoDictionary = {10: 'TutorialsPoint', 12: 'Python', 14: 'Codes'} # Printing the value of key 'hello' from a dictionary # A KeyError is raised as the hello key is NOT present in the dictionary print("The value of key 'hello' from a dictionary:", demoDictionary['hello'])

輸出

Traceback (most recent call last):
  File "main.py", line 6, in 
    print("The value of key 'hello' from a dictionary:", demoDictionary['hello'])
KeyError: 'hello'

處理KeyError

以下程式碼使用try-except塊處理上述程式碼中返回的KeyError

示例

如果發生任何錯誤,則會執行except塊語句。

# input dictionary demoDictionary = {10: 'TutorialsPoint', 12: 'Python', 14: 'Codes'} # Handling KeyError using try-except blocks try: print(demoDictionary['hello']) except KeyError: print("No, The key for Value 'Hello' does not exist in the dictionary. Please check")

輸出

No, The key for Value 'Hello' does not exist in the dictionary. Please check

方法2:使用dict.get()方法

我們可以使用字典的get()方法從字典中獲取指定鍵的值,而不會在鍵不存在時丟擲錯誤。

作為第一個引數,指定鍵。如果鍵存在,則返回對應的值;否則,返回None。

示例1

以下程式使用dict.get()方法返回從輸入字典中給定鍵的值的索引:

# input dictionary demoDictionary = {10: 'TutorialsPoint', 12: 'Python', 14: 'Codes'} # Printing the value of key 10 from a dictionary using get() method print("The value of key 10 from a dictionary:", demoDictionary.get(10)) # Printing the value of key 'hello' from a dictionary # As the hello key does not exist in the dictionary, it returns None print("The value of key 'hello' from a dictionary:", demoDictionary.get('hello'))

輸出

The value of key 10 from a dictionary: TutorialsPoint
The value of key 'hello' from a dictionary: None

在第二個引數中,您可以定義如果鍵不存在要返回的預設值。

示例2

以下程式使用dict.get()方法返回使用者給定的訊息(作為第二個引數傳遞),如果鍵不存在於字典中:

# input dictionary demoDictionary = {10: 'TutorialsPoint', 12: 'Python', 14: 'Codes'} # Printing the value of key 'hello' from a dictionary # As the hello key does not exist in the dictionary, it returns the user-given message print("The value of key 'hello' from a dictionary:", demoDictionary.get('hello', "The Key does not exist"))

輸出

The value of key 'hello' from a dictionary: The Key does not exist

方法3:使用keys()函式

以下程式使用keys()方法返回從輸入字典中給定鍵的值的索引:

以下是執行所需任務的演算法/步驟:

  • 使用keys()函式遍歷字典鍵(dict.keys()方法提供一個檢視物件,按插入順序顯示字典中所有鍵的列表)。

  • 檢查給定鍵是否等於迭代器值,如果相等,則列印其對應的值

示例

# input dictionary demoDictionary = {10: 'TutorialsPoint', 12: 'Python', 14: 'Codes'} # enter the key for which the value to be obtained givenkey= 10 # Traversing the keys of the dictionary for i in demoDictionary.keys(): # checking whether the value of the iterator is equal to the above-entered key if(i==givenkey): # printing the value of the key print(demoDictionary[i])

輸出

TutorialsPoint

方法4:使用items()函式

示例

以下程式使用items()方法返回從輸入字典中給定鍵的值的索引:

# input dictionary demoDictionary = {10: 'TutorialsPoint', 12: 'Python', 14: 'Codes'} givenkey= 12 # Traversing in the key-value pairs of the dictionary using the items() function for key,val in demoDictionary.items(): # checking whether the key value of the iterator is equal to the above-entered key if(key==givenkey): print(val)

輸出

Python

結論

在本文中,我們學習瞭如何使用四種不同的方法獲取字典鍵的值。我們還學習瞭如何在字典中不存在鍵時處理錯誤。

更新於:2023年10月31日

32K+ 次瀏覽

啟動您的職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.