如何从JSON文件提取指定键值对更新Python字典实现背包物品添加
解决方案
你只需要在读取JSON文件后,仅提取传入的对应物品键值对存入库存字典即可,不需要遍历全量键值对,优化后的代码如下:
import json inventory = {} def addInventory(item_name): # 使用with上下文管理器自动处理文件关闭,避免资源泄露 with open('examine.json', 'r', encoding='utf-8') as f: item_dic = json.load(f) # 先判断物品是否在JSON配置中存在,避免抛出KeyError if item_name in item_dic: inventory[item_name] = item_dic[item_name] else: print(f"拾取失败:物品{item_name}不存在于库存配置中") x = 'egg' addInventory(x) print(inventory)
运行后输出结果为:
{'egg': 'This smells funny.'}
代码修改说明
- 将原函数参数名从
args改为表意更清晰的item_name,方便后续维护 - 用
with语法管理文件打开操作,不需要手动调用close()方法,更安全 - 增加了物品存在性判断,避免传入不存在的物品名时报错
- 不再全量更新
inventory字典,仅赋值指定键值对,符合只添加拾取物品的需求
如果你确实需要用for循环实现(比如后续要支持一次拾取多个物品的场景),可以把入参改成列表,写法如下:
def addInventory(item_list): with open('examine.json', 'r', encoding='utf-8') as f: item_dic = json.load(f) for item in item_list: if item in item_dic: inventory[item] = item_dic[item] # 一次拾取多个物品的调用示例 addInventory(['egg', 'stick'])
内容的提问来源于stack exchange,提问作者Mordork
相关产品推荐
相关产品推荐

