已知字典D={"nam'":"Zhangsan", "sex":"M","address":"Nanjing","phone":"123456"},请设计代码分别实现以下功能: (1) 输出字典D的所有键值对; (2)输出D的phone值; (3)修改D的address值为Shanghai; (4)添加键值对age: 20; (5)删除字典D的sex键值对。使用Python语言程序
时间: 2023-07-19 08:42:25 浏览: 287
下面是实现以上功能的Python代码:
```
# 定义字典D
D = {"name": "Zhangsan", "sex": "M", "address": "Nanjing", "phone": "123456"}
# 输出所有键值对
print("所有键值对:", D.items())
# 输出phone的值
print("phone的值:", D["phone"])
# 修改address的值为Shanghai
D["address"] = "Shanghai"
print("修改后的字典:", D)
# 添加age键值对
D["age"] = 20
print("添加age键值对后的字典:", D)
# 删除sex键值对
del D["sex"]
print("删除sex键值对后的字典:", D)
```
输出结果如下:
```
所有键值对: dict_items([('name', 'Zhangsan'), ('sex', 'M'), ('address', 'Nanjing'), ('phone', '123456')])
phone的值: 123456
修改后的字典: {'name': 'Zhangsan', 'sex': 'M', 'address': 'Shanghai', 'phone': '123456'}
添加age键值对后的字典: {'name': 'Zhangsan', 'sex': 'M', 'address': 'Shanghai', 'phone': '123456', 'age': 20}
删除sex键值对后的字典: {'name': 'Zhangsan', 'address': 'Shanghai', 'phone': '123456', 'age': 20}
```
阅读全文