在遍历字典时,可以使用dict.get()
方法来获取键对应的值。如果键不存在,get()
方法会返回None或者指定的默认值,而不会抛出KeyError异常。
以下是一个示例代码:
my_dict = {'A': 1, 'B': 2, 'C': 3}
search_keys = ['A', 'D', 'B', 'E']
for key in search_keys:
value = my_dict.get(key)
if value is not None:
print(f"The value for key '{key}' is {value}")
else:
print(f"The key '{key}' does not exist in the dictionary")
输出结果:
The value for key 'A' is 1
The key 'D' does not exist in the dictionary
The value for key 'B' is 2
The key 'E' does not exist in the dictionary
在上面的示例中,my_dict.get(key)
方法会尝试获取key
对应的值,如果键不存在,则返回None
。这样就避免了获取错误搜索键对应的值时抛出KeyError
的情况。
下一篇:遍历字典以创建列表