已知字典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-06-03 22:05:22 浏览: 209
python 获取字典键值对的实现
好的,我明白了。以下是您需要的Python代码实现:
```python
# 定义字典D
D = {"name":"Zhangsan", "sex":"M", "address":"Nanjing", "phone":"123456"}
# (1) 输出字典D的所有键值对
for key, value in D.items():
print(key, ":", value)
# (2) 输出D的phone值
print("phone value:", D["phone"])
# (3) 修改D的address值为Shanghai
D["address"] = "Shanghai"
print("modified D:", D)
# (4) 添加键值对age: 20
D["age"] = 20
print("after adding age:", D)
# (5) 删除字典D的sex键值对
del D["sex"]
print("after deleting sex:", D)
```
希望这能帮到您!
阅读全文