定義一個函數“lookup_key(d, k)”用於從dictionary “d”中找尋key “k”︒請用try和except在找不到“k”時回報問題;用else處理找到“k”時print出k對應的value;用finally處理最終print出“lookup finish”︒
时间: 2024-11-30 12:29:06 浏览: 14
你可以定义一个名为`lookup_key`的函数,它接受两个参数:一个字典`d`和一个键`k`。下面是一个Python函数的实现,符合您给出的要求:
```python
def lookup_key(d, k):
try:
value = d[k]
print(f"Key '{k}' maps to value: {value}")
except KeyError:
print(f"Error: Key '{k}' not found in the dictionary.")
else:
pass # No need for an explicit 'pass', as printing happens inside the try block
finally:
print("Lookup finished.")
# 示例用法
my_dict = {"name": "John", "age": 30}
lookup_key(my_dict, "name") # Will print the value associated with key "name"
lookup_key(my_dict, "country") # Will print "Error: Key 'country' not found in the dictionary."
```
在这个函数中,我们首先尝试从字典中获取给定的键。如果键存在,它的值会被打印出来。如果键不存在,则会引发`KeyError`异常,此时我们会捕获这个异常并输出错误信息。无论是否发生异常,最后都会执行`finally`块里的内容,即打印"Lookup finished."。
阅读全文