深入解析Python字典的增删查操作
在Python中,字典是一种可变容器模型,且可存储任意类型对象。字典的增删查操作如下:
增(add item):
- 字典使用
update()
方法添加新键值对,或者直接用键来设置值。
```python添加一个键值对
dict = {“name”: “John”, “age”: 30}
dict[“job”] = “Engineer”
print(dict) # 输出:{‘name’: ‘John’, ‘age’: 30, ‘job’: ‘Engineer’}
或者用直接键来设置值
dict[“address”] = “123 Main St”
print(dict) # 输出:{‘name’: ‘John’, ‘age’: 30, ‘job’: ‘Engineer’, ‘address’: ‘123 Main St’}
```- 字典使用
删(remove item):
- 使用
del
关键字删除键值对,或者使用pop()
方法删除并返回指定的键对应的值。
```python删除键值对
dict = {“name”: “John”, “age”: 30}
del dict[“age”]
print(dict) # 输出:{‘name’: ‘John’, ‘age’: None}
使用pop()方法删除并返回指定键的值
job = dict.pop(“job”)
print(job, dict) # 输出:”Engineer” ({‘name’: ‘John’, ‘age’: 30, ‘job’: None}})
```- 使用
查(search for key):
- 使用
in
关键字检查键是否存在于字典中。
```python
dict = {“name”: “John”, “age”: 30}
print(“Age” in dict) # 输出:True
job = “Engineer”
if job in dict:print(f"{job}" is present in the dictionary))
else:
print(f"{job}" is not present in the dictionary"))
```
- 使用
这就是Python字典的增删查操作。
还没有评论,来说两句吧...