Python作业本——第5章 字典和结构化数据
习题
1.
1 |
2.
{'fow': 42}
3.字典是无序的
4.报错 (KeyError)
5.第一种是既搜索键又搜索值,第二种值搜索键 没有区别,in操作符检查一个值是不是字典的一个键。
6.第一种是既搜索键又搜索值,第二种值搜索值 第一种检查键
7.
spam.setdefault('color', 'black')
8.pprint模块的pprint函数
实践项目
5.6.1 好玩游戏的物品清单
1 stuff = {'rope': 1, 'torch': 6, 'gold coin':42, 'dagger': 1, 'arrow': 12} 2 3 def displayInventory(inventory): 4 print("inventory:") 5 item_total = 0 6 for k, v in inventory.items(): 7 print(str(v) + ' ' + k) 8 item_total += v 9 print("Total number of items: " + str(item_total)) 10 11 displayInventory(stuff)
5.6.2 列表到字典的函数,针对好玩游戏物品清单
1 def displayInventory(inventory): 2 print("inventory:") 3 item_total = 0 4 for k, v in inventory.items(): 5 print(str(v) + ' ' + k) 6 item_total += v 7 print("Total number of items: " + str(item_total)) 8 9 def addToInventory(inventory, addedItems): 10 for i in addedItems: 11 if i in inventory: 12 inventory[str(i)] = inventory[str(i)] + 1 # 若之前就存在该物品,就将该物品的数量加1 13 else: 14 inventory[str(i)] = 1 # 若之前不存在该物品,就在字典里加上1个该物品 15 16 inv = {'gold coin': 42, 'rope': 1} 17 dragonLoot = ['gold coin', 'dragger', 'gold coin', 'gold coin', 'ruby'] 18 19 addToInventory(inv, dragonLoot) 20 displayInventory(inv)
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Java 中堆内存和栈内存上的数据分布和特点
· 开发中对象命名的一点思考
· .NET Core内存结构体系(Windows环境)底层原理浅谈
· C# 深度学习:对抗生成网络(GAN)训练头像生成模型
· .NET 适配 HarmonyOS 进展
· 手把手教你更优雅的享受 DeepSeek
· 腾讯元宝接入 DeepSeek R1 模型,支持深度思考 + 联网搜索,好用不卡机!
· AI工具推荐:领先的开源 AI 代码助手——Continue
· 探秘Transformer系列之(2)---总体架构
· V-Control:一个基于 .NET MAUI 的开箱即用的UI组件库