字典练习题
统计网站访问量
题目描述
已知一周访问量字典
visits = {'周一': 1200, '周二': 1500, '周三': 1300, '周四': 1800, '周五': 2000},遍历字典并按 “周 x:xxx 次访问” 的格式逐行输出每日访问量。
输出示例
周一:1200次访问
周二:1500次访问
周三:1300次访问
周四:1800次访问
周五:2000次访问
实现代码
# 网站每日访问量
visits = {'周一': 1200,'周二': 1500,'周三': 1300,'周四': 1800,'周五': 2000
}
# 逐行输出访问量
for day in visits:print(f"{day}:{visits[day]}次访问")访问嵌套字典的值
题目描述
字典
person = {'name': '小红', 'info': {'height': 165, 'weight': 50}}
中,'info'对应的值是一个包含身高和体重的子字典。请输出该人的身高。
输出示例
姓名:小红
身高:165厘米
体重:50公斤
实现代码
person = {'name': '小红', 'info': {'height': 165, 'weight': 50}}# 分别访问字典中的所有值并按格式输出
print(f"姓名:{person['name']}")
print(f"身高:{person['info']['height']}厘米")
print(f"体重:{person['info']['weight']}公斤")批量修改字典值
题目描述
价格字典
prices = {'苹果': 5.0, '香蕉': 3.0, '橙子': 4.0},
因促销活动,所有水果价格打 9 折。请修改字典中所有商品的价格(结果保留 1 位小数),并输出修改后的字典。
输出示例
{'苹果': 4.5, '香蕉': 2.7, '橙子': 3.6}
实现代码
prices = {'苹果': 5.0, '香蕉': 3.0, '橙子': 4.0}
# 遍历所有商品,价格打9折
for fruit in prices:prices[fruit] = round(prices[fruit] * 0.9, 1)
print(prices)更新商品信息
题目描述
商品 goods = {'name': '卫衣'},添加'price': 199,再用update修改价格为159并添加'color': '灰色'。输出结果。
输出示例
{'name': '卫衣', 'price': 159, 'color': '灰色'}
实现代码
goods = {'name': '卫衣'}
goods['price'] = 199 # 添加价格
goods.update({'price': 159, 'color': '灰色'}) # 修改+添加
print(goods)超市商品管理
题目描述
模拟超市商品库存管理:
初始商品字典
goods = {'苹果': 50, '香蕉': 30, '橙子': 40};添加商品 “葡萄”,库存 25;
将香蕉库存修改为 20;
删除橙子;
遍历字典,按 “商品:库存 xx” 格式输出所有商品。
输出示例
苹果:库存50
香蕉:库存20
葡萄:库存25
实现代码
# 初始商品字典
goods = {'苹果': 50, '香蕉': 30, '橙子': 40}# 添加葡萄
goods['葡萄'] = 25# 修改香蕉库存
goods['香蕉'] = 20# 删除橙子
del goods['橙子']# 遍历输出
for item in goods:print(f"{item}:库存{goods[item]}")单词频率统计
题目描述
统计一段文本中每个单词出现的频率,忽略大小写和标点符号。
示例
输入: "Hello world, hello Python! World is beautiful."
输出: {'hello': 2, 'world': 2, 'python': 1, 'is': 1, 'beautiful': 1}
实现代码
# 单词频率统计
text = "Hello world, hello Python! World is beautiful. Python is awesome."# 清理文本:转小写,去除标点
import string
cleaned_text = text.lower().translate(str.maketrans('', '', string.punctuation))# 分割单词
words = cleaned_text.split()# 统计频率
word_freq = {}
for word in words:if word in word_freq:word_freq[word] += 1else:word_freq[word] = 1
print(word_freq)购物车商品管理
题目描述
初始购物车字典为
{'apple': 3, 'banana': 5, 'orange': 2},完成以下操作:
删除键为
'banana'的商品;删除最后添加到购物车的商品;
新增商品
'grape',数量为 4;若购物车中商品种类大于 1 种,清空购物车;
输出最终的购物车(若为空则输出 “购物车为空”)。
输出示例
购物车为空
实现代码
cart = {'apple': 3, 'banana': 5, 'orange': 2}# 删除banana
cart.pop('banana')# 删除最后添加的商品(orange)
cart.popitem()# 新增grape
cart['grape'] = 4# 判断是否清空
if len(cart) > 1:cart.clear()# 输出结果
print(cart if cart else "购物车为空")