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, 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
结论
在本文中,我们学习了四种不同的方法来获取字典键的值。我们还学习了在字典中不存在键时如何处理错误。
极客笔记