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)
复制代码

 

posted @   yuzhenzero  阅读(336)  评论(0编辑  收藏  举报
编辑推荐:
· Java 中堆内存和栈内存上的数据分布和特点
· 开发中对象命名的一点思考
· .NET Core内存结构体系(Windows环境)底层原理浅谈
· C# 深度学习:对抗生成网络(GAN)训练头像生成模型
· .NET 适配 HarmonyOS 进展
阅读排行:
· 手把手教你更优雅的享受 DeepSeek
· 腾讯元宝接入 DeepSeek R1 模型,支持深度思考 + 联网搜索,好用不卡机!
· AI工具推荐:领先的开源 AI 代码助手——Continue
· 探秘Transformer系列之(2)---总体架构
· V-Control:一个基于 .NET MAUI 的开箱即用的UI组件库
点击右上角即可分享
微信分享提示