Python字典操作:更新、删除及合并实践
在Python中,字典是一种可变容器模型,可以存储任意类型的数据。以下是如何更新、删除和合并字典的几种常见方法:
更新键值对
dict1[“email”] = “john@example.com”
print(dict1) # 输出: {‘name’: ‘John’, ‘age’: 30, ‘email’: ‘john@example.com’}
2. 删除字典中的项:
```python
# 原始字典
dict1 = {"name": "John", "age": 30}
# 删除键值对
if "email" in dict1:
del dict1["email"]
print(dict1) # 输出: {'name': 'John', 'age': 30}
原始字典2
dict2 = {“key2”: “new_value2”, “key3”: “value3”}
合并字典
merged_dict = {dict1, dict2} if dict1 and dict2 else dict1 or dict2
print(merged_dict) # 输出: {‘key1’: ‘value1’, ‘key2’: ‘new_value2’, ‘key3’: ‘value3’}
```
注意:在合并字典时,如果有重复的键,后面的值会覆盖前面的值。
还没有评论,来说两句吧...