Python中字典的增删改查问题
在Python中,字典是一种可变容器模型,可以存储任意类型的数据。下面分别介绍字典的增、删、改查操作:
添加键值对
dict_instance[“key”] = “value”
print(dict_instance) # 输出: {‘key’: ‘value’}
2. 删(删除指定的键值对):
```python
# 删除键值对
if "key" in dict_instance:
del dict_instance["key"]
print(dict_instance) # 输出: {}
print(dict_instance) # 输出: {‘new_key’: ‘new_value’}
4. 查(根据键查找对应的值,如果不存在则返回None):
```python
# 查找特定的键值对
value = dict_instance.get("key", None)
if value is not None:
print(f"Found key '{'key'}'}, value: {value}) # 输出: Found key 'key', value: value
else:
print("Key not found in the dictionary.") # 输出: Key not found in the dictionary.
以上就是Python中字典增删改查的操作。
还没有评论,来说两句吧...