Python中字典操作错误:键值对查找和更新示例
在Python中,字典是一种可变容器模型,它通过键来存取元素。以下是一些关于字典操作的示例:
查找键对应的值:
dict = {'name': 'John', 'age': 30}
print(dict['name']) # 输出:John
更新键对应的值:
dict = {'name': 'John', 'age': 30}
dict['age'] = 31 # 更新年龄为31
print(dict) # 输出:{'name': 'John', 'age': 31}
检查键是否存在:
dict = {'name': 'John', 'age': 30}
if 'name' in dict:
print(f"Name: {dict['name']]}")
else:
print("Name not found in the dictionary.")
以上代码展示了字典的键值对查找、更新和检查键是否存在等操作。
还没有评论,来说两句吧...