Python字典的增删查操作示例
在Python中,字典是一种可变容器模型,允许存储任意类型对象的键值对。以下是对字典增删查操作的示例:
- 增加键值对:
```python
dict_name = {‘name’: ‘Alice’, ‘age’: 25}
增加键’city’和对应的值’New York’
dict_name[‘city’] = ‘New York’
print(dict_name) # 输出:{‘name’: ‘Alice’, ‘age’: 25, ‘city’: ‘New York’}
2. 删除键值对:
```python
dict_name = {'name': 'Alice', 'age': 25}
# 删除键'city'
if 'city' in dict_name:
del dict_name['city']
print(dict_name) # 输出:{'name': 'Alice', 'age': 25}
- 查找特定键的值:
```python
dict_name = {‘name’: ‘Alice’, ‘age’: 25}
查找键’age’
if ‘age’ in dict_name:
print(“Age:”, dict_name[‘age’])) # 输出:Age: 25
else:
print(“Key not found: ‘age’”)) # 输出:Key not found: ‘age’
```
以上就是Python字典增删查操作的示例。
还没有评论,来说两句吧...