如何从Python字典中获取给定键的值?
在本文中,我们将向您展示如何从Python字典中获取给定键的值。以下是4种不同的方法,可完成此任务 –
- 使用字典索引
-
使用dict.get()方法
-
使用keys()函数
-
使用items()函数
假设我们已经创建了一个包含键值对的字典。我们将从给定的输入字典返回指定键的值。
阅读更多:Python 教程
方法1:使用字典索引
在Python中,我们可以使用dict[key]从字典中检索值。
算法(步骤)
要执行所需的任务,应遵循以下算法/步骤 –
- 创建一个变量来存储输入字典
-
通过将键值传递到[]括号中的输入字典中获取指定键的值。
-
打印给定键的结果值。
示例1
以下程序使用dict[key]方法从输入字典返回给定键的值 –
# 输入字典
demoDictionary = {10: 'TutorialsPoint', 12: 'Python', 14: 'Codes'}
# 从字典中获取键10的值
print("The value of key 10 from dictionary is =", demoDictionary[10])
输出
The value of key 10 from dictionary is = TutorialsPoint
如果给定输入字典中不存在键,则会引发 键错误 。
示例2
在下面的代码中,键“hello”不在输入列表中。 因此,当我们尝试打印键“hello”的值时,会返回 一个 键错误 。-
# 输入字典
demoDictionary = {10: 'TutorialsPoint', 12: 'Python', 14: 'Codes'}
# 从字典中获取键'hello'的值
# 当hello键不存在于字典中时,会引发KeyError
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块处理上述代码返回的 键错误 -
例子
如果发生任何错误,except块语句将被执行。 –
# 输入字典
demoDictionary = {10: 'TutorialsPoint', 12: 'Python', 14: 'Codes'}
# 使用try-except语句处理KeyError
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
方法二: 使用dict.get()方法
我们可以使用字典的get()方法获取指定键的值,如果键不存在,则不会引发错误。
作为第一个参数,指定键。如果键存在,则返回相应的值; 否则返回None。
示例1
以下程序使用dict.get()方法返回给定键的值的索引,输入字典−
# 输入字典
demoDictionary = {10: 'TutorialsPoint', 12: 'Python', 14: 'Codes'}
# 使用get()方法从字典中打印键10的值
print("The value of key 10 from a dictionary:", demoDictionary.get(10))
# 从字典中打印键为'hello'的值
# 因为hello键不存在于字典中,所以返回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()方法返回第二个参数中传递的用户给定消息,如果键不存在于字典中,则返回该消息−
# 输入字典
demoDictionary = {10: 'TutorialsPoint', 12: 'Python', 14: 'Codes'}
# 从字典中打印键为'hello'的值
# 因为hello键不存在于字典中,所以返回用户给定的消息
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
方法三: 使用keys()函数
以下程序使用keys()方法从输入字典中返回给定键的值的索引−
以下是执行所需任务的算法/步骤−
- 使用keys()函数在字典中遍历键(dict.keys()方法提供视图对象,按插入顺序显示字典中所有键的列表)。
-
检查给定的键是否等于迭代器的值,如果相等,则打印其对应的值。
示例
#输入字典
demoDictionary={10:'TutorialsPoint',12:'Python',14:'Codes'}
#输入要获取的键的值
givenkey=10
#遍历字典的键
for iindemoDictionary.keys():
#检查迭代器的值是否等于上面输入的键
if(i==givenkey):
#打印键的值
print(demoDictionary[i])
输出
TutorialsPoint
方法4:使用items()函数
示例
以下程序使用items()方法返回给定键的值的索引。
#输入字典
demoDictionary={10:'TutorialsPoint',12:'Python',14:'Codes'}
givenkey=12
#使用items()函数遍历字典中的键-值对
for key,valindemoDictionary.items():
#检查迭代器的键值是否等于上面输入的键
if(key==givenkey):
print(val)
输出
Python
结论
在本文中,我们学习了如何使用四种不同的方法获取字典键的值。我们还学习了如何处理字典中不存在的键的错误。