字典操作。建立一个月份与天数的字典monthdays,月份为‘Jan’,‘Feb’,‘Mar’,‘Apr’,‘May’,‘Jun’,‘Jul’,‘Aug’,‘Sep’,‘Oct’,‘Nov’,‘Dec’,每个月对应的天数为:31,28,31,30,31,30,31,31,30,31,30,31,完成以下操作: (1)输出字典monthdays的键序列 (2)输出字典monthdays的值序列 (3)输出字典monthdays的键值对序列 (4)输入月份比如‘May’,获取键‘May’对应的值 (5)修改键‘Feb’的值为29 (6)创建一个新的字典d={"a1":35,"a2":35},将其包含的键值对更新到字典monthdays中 (7)删除键为‘a1’的键值对
时间: 2023-08-06 11:13:07 浏览: 103
只需要用一张图片素材文档选择器.zip
下面是对应的 Python 代码实现:
```python
# 建立月份与天数的字典
monthdays = {
'Jan': 31,
'Feb': 28,
'Mar': 31,
'Apr': 30,
'May': 31,
'Jun': 30,
'Jul': 31,
'Aug': 31,
'Sep': 30,
'Oct': 31,
'Nov': 30,
'Dec': 31
}
# 输出字典的键序列
print("Keys:", list(monthdays.keys()))
# 输出字典的值序列
print("Values:", list(monthdays.values()))
# 输出字典的键值对序列
print("Items:", list(monthdays.items()))
# 输入月份获取对应的天数
month = input("Enter a month: ")
print("Days in", month, ":", monthdays.get(month))
# 修改键'Feb'对应的值为29
monthdays['Feb'] = 29
print("Updated monthdays:", monthdays)
# 将字典d中的键值对更新到monthdays中
d = {"a1": 35, "a2": 35}
monthdays.update(d)
print("Updated monthdays:", monthdays)
# 删除键为'a1'的键值对
del monthdays['a1']
print("Updated monthdays:", monthdays)
```
输出结果如下:
```
Keys: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
Values: [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
Items: [('Jan', 31), ('Feb', 28), ('Mar', 31), ('Apr', 30), ('May', 31), ('Jun', 30), ('Jul', 31), ('Aug', 31), ('Sep', 30), ('Oct', 31), ('Nov', 30), ('Dec', 31)]
Enter a month: May
Days in May : 31
Updated monthdays: {'Jan': 31, 'Feb': 29, 'Mar': 31, 'Apr': 30, 'May': 31, 'Jun': 30, 'Jul': 31, 'Aug': 31, 'Sep': 30, 'Oct': 31, 'Nov': 30, 'Dec': 31}
Updated monthdays: {'Jan': 31, 'Feb': 29, 'Mar': 31, 'Apr': 30, 'May': 31, 'Jun': 30, 'Jul': 31, 'Aug': 31, 'Sep': 30, 'Oct': 31, 'Nov': 30, 'Dec': 31, 'a1': 35, 'a2': 35}
Updated monthdays: {'Jan': 31, 'Feb': 29, 'Mar': 31, 'Apr': 30, 'May': 31, 'Jun': 30, 'Jul': 31, 'Aug': 31, 'Sep': 30, 'Oct': 31, 'Nov': 30, 'Dec': 31, 'a2': 35}
```
阅读全文