5.6.3 列表到字典的函数,针对好玩游戏的物品清单

本文介绍了在开发游戏物品清单管理程序`inventorypy`时遇到的问题,即在遍历列表内字典时导致的`RuntimeError`:字典在迭代过程中大小发生了变化。强调了在遍历字典时不能修改字典这一关键知识点,并提醒开发者在处理列表嵌套字典或字典嵌套列表的情况时要注意避免此类错误。
摘要由CSDN通过智能技术生成
'''
这个代码段有两个函数,
第一个函数displayInventory(Inventory)用于展示字典。
键是物品名称,值是物品数量。展示模式是v个k。
第二个函数addToInventory(inventory,addedItems)用于更新字典。
更新方式是遍历列表,对照字典键,有就+1,没有就加进去。
'''
def displayInventory(inventory):#展示清单
	print('Inventory:')
	item_total=0
	for k,v in inventory.items():
		print(str(v)+' '+k)
		item_total+=v
	print('Total number of items: '+str(item_total))
def addToInventory(inventory,addedItems):#加进清单,就是更新字典
	for i in addedItems:#遍历列表addedItems
		if i in inventory:
			inventory[i]+=1
		else:
			inventory[i]=1
	return inventory#返回更新好的字典
inv={'gold coin':42,'rope':1}
dragonLoot=['gold coin','dragger','gold coin','gold coin','ruby']
inv=addToInventory(inv,dragonLoot)#返回更新好的字典到inv
displayInventory(inv)#展示字典inv
	

 上面这是   inventorypy   文件

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值