Python中如何根据ID从API返回的JSON库存中查询物品数量?
解决方法
原代码问题分析
你这段代码的核心错误在于:
inventory_data.items()是遍历整个JSON字典的键值对,这里只会得到("inventory", [物品列表])这一组键值,key是字符串"inventory",自然无法通过key["ID"]访问物品属性,会直接抛出类型错误。- 代码中没有正确获取循环索引的逻辑,完全偏离了遍历物品列表的需求。
方法一:单次查询直接遍历列表
如果只是偶尔查询一次,直接遍历inventory列表匹配ID即可:
# 假设inventory_data是API返回的完整JSON数据 target_id = 10 result_quantity = None # 遍历inventory列表中的每个物品 for item in inventory_data["inventory"]: if item["ID"] == target_id: result_quantity = item["quantity"] break # ID唯一,找到后立即终止循环提升效率 # 输出结果 if result_quantity is not None: print(f"ID {target_id} 的物品数量:{result_quantity}") else: print(f"未找到ID为 {target_id} 的物品")
方法二:构建映射字典(适合多次查询)
如果需要频繁根据ID查询,先把物品列表转换成ID为键、数量为值的字典,后续查询可以直接通过ID快速取值(时间复杂度O(1)):
# 从API数据中提取inventory列表,构建ID到数量的映射 id_quantity_map = {item["ID"]: item["quantity"] for item in inventory_data["inventory"]} # 查询指定ID的数量 target_id = 10 if target_id in id_quantity_map: print(f"ID {target_id} 的物品数量:{id_quantity_map[target_id]}") else: print(f"未找到ID为 {target_id} 的物品")
内容的提问来源于stack exchange,提问作者Kai
相关产品推荐
相关产品推荐

