#使用{}创建一个空字典 my_dict = {} #或者使用dict()函数创建一个空字典 my_dict = dict()
my_dict = {'Name': 'Tom', 'Age': 25}
my_dict = {'Name': 'Tom', 'Age': 25} print("姓名:", my_dict['Name']) print("年龄:", my_dict['Age'])
姓名: Tom 年龄: 25
my_dict = {'Name': 'Tom', 'Age': 25} my_dict['Age'] = 30 print("修改后的年龄为:", my_dict['Age'])
修改后的年龄为: 30
my_dict = {'Name': 'Tom', 'Age': 25} del my_dict['Age'] print("删除后的字典为:", my_dict)
删除后的字典为: {'Name': 'Tom'}
my_dict = {'Name': 'Tom', 'Age': 25} for key, value in my_dict.items(): print("Key:", key, " Value:", value)
Key: Name Value: Tom Key: Age Value: 25
my_dict = {'Name': 'Tom', 'Age': 25} for key in my_dict.keys(): print("Key:", key)
Key: Name Key: Age
my_dict = {'Name': 'Tom', 'Age': 25} for value in my_dict.values(): print("Value:", value)
Value: Tom Value: 25
#创建字典,存储不同城市每天的气温 weather_dict = {'北京': [10, 6, 7, 8, 5, 7, 6], '上海': [16, 17, 18, 16, 15, 17, 16], '深圳': [24, 25, 26, 24, 23, 26, 27], '广州': [26, 27, 28, 27, 26, 30, 25], '杭州': [15, 16, 17, 19, 18, 20, 21], '武汉': [17, 19, 20, 18, 18, 21, 20]} #1. 查询某个城市的某一天的温度 print("北京第3天的温度为:", weather_dict['北京'][2]) #2. 查询某个城市的最高温度和最低温度 print("广州最高温度为:", max(weather_dict['广州'])) print("广州最低温度为:", min(weather_dict['广州'])) #3. 查询某段时间内某个城市的平均温度 start_day = 2 end_day = 5 city = '深圳' temperature_list = weather_dict[city][start_day:end_day+1] avg_temperature = sum(temperature_list)/len(temperature_list) print("{}第{}到{}天的平均气温为:{}".format(city, start_day, end_day, avg_temperature)) #4. 查询某段时间内所有城市的平均温度 start_day = 2 end_day = 5 avg_temperature_dict = {} for city, temperature_list in weather_dict.items(): temperature_list = temperature_list[start_day:end_day+1] avg_temperature = sum(temperature_list)/len(temperature_list) avg_temperature_dict[city] = round(avg_temperature, 1) print("{}到{}天各城市平均气温:{}".format(start_day, end_day, avg_temperature_dict))
北京第3天的温度为: 7 广州最高温度为: 30 广州最低温度为: 25 深圳第2到5天的平均气温为:24.5 2到5天各城市平均气温:{'北京': 6.5, '上海': 16.5, '深圳': 24.5, '广州': 26.2, '杭州': 18.5, '武汉': 19.5}
标签: 推广