Python字典操作:如何添加、修改和查询字典内容
在Python中,字典是一种可变容器模型,用于存储键值对。以下是如何添加、修改和查询字典的内容:
添加元素(键值对):
# 创建一个空字典
dict = {}
# 添加键值对
dict["key1"] = "value1"
dict["key2"] = 42
print(dict) # 输出: {'key1': 'value1', 'key2': 42}
修改元素(键值对):
dict["key1"] = "new value1"
print(dict) # 输出: {'key1': 'new value1', 'key2': 42}
查询元素(键值对):
key_to_find = "key1"
if key_to_find in dict:
value = dict[key_to_find]]
print(f"The value for '{key_to_find}'} is {value}.")
else:
print(f"'{key_to_find}'}' not found in the dictionary.")
以上就是在Python中添加、修改和查询字典内容的操作。
还没有评论,来说两句吧...