如何从 Python 字典中获取给定键的值?
在本文中,我们将向您展示如何从 Python 字典中获取给定键的值。以下是完成此任务的 4 种不同方法 -
使用字典索引
使用 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, inprint("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
结论
在本文中,我们学习了如何使用四种不同的方法获取字典键的值。我们还学习了当字典中不存在键时如何处理错误。