Python字典操作:查找,更新与删除示例
在Python中,字典是一种可变容器模型,类似于现实生活中使用的各种盒子。字典的每个键值对用冒号 : 分割,每对键值对之间用逗号 , 分割。
以下是一些查找、更新和删除字典内容的示例:
查找键为’name’的值
value = dict.get(‘name’)
print(value) # 输出: John
如果键不存在,get()方法将返回None
value = dict.get(‘city’) # 假设 city 在字典中
print(value) # 输出: None
2. 更新:
```python
dict = {'name': 'John', 'age': 30}
# 使用update()方法更新字典
dict.update({'address': '123 Main St'}})
print(dict)
# 输出:
# {'name': 'John', 'age': 30, 'address': '123 Main St'}
- 删除:
```python
dict = {‘name’: ‘John’, ‘age’: 30}
使用pop()方法删除并返回指定的键值对,如果键不存在,则返回None和None
value = dict.pop(‘age’)
if value is not None:
print(“Deleted age: “, value)
else:
print(“Key ‘age’ not found in dictionary.”)
```
以上就是Python字典操作的一些基本示例。
还没有评论,来说两句吧...