从API返回字典打印食材列表时触发字符串类型索引错误
解决"list indices must be integers or slices, not str"错误
错误原因
Edamam API返回的JSON数据里,hits字段是一个列表(包含所有匹配的食谱结果),而你直接用字符串'recipe'去索引这个列表,自然会触发类型错误——列表只能用整数或切片做索引,不能用字符串。
修复方案
根据你的需求,有两种处理方式:
1. 获取第一个匹配的食谱
如果只需要第一个搜索结果的食材,先取hits列表的第一个元素(索引0),再访问recipe字段:
def get_chosen_recipe(): chosen_recipe = input("What recipe do you want to cook? ") app_id = "<my app id>" app_key = "<my app key>" url = 'https://api.edamam.com/search?q={}&app_id={}&app_key={}'.format(chosen_recipe, app_id, app_key) response = requests.get(url) response.raise_for_status() # 若HTTP请求失败则抛出错误 choice = response.json() # 先检查是否有匹配的食谱结果 if choice.get('hits'): # 取第一个匹配的食谱,再提取食材列表 ingredients = choice['hits'][0]['recipe']['ingredientLines'] pprint(ingredients) else: print("No ingredients found. Please try a different recipe.")
2. 获取所有匹配的食谱
如果要输出所有搜索结果的食材,需要遍历hits列表:
def get_chosen_recipe(): chosen_recipe = input("What recipe do you want to cook? ") app_id = "<my app id>" app_key = "<my app key>" url = 'https://api.edamam.com/search?q={}&app_id={}&app_key={}'.format(chosen_recipe, app_id, app_key) response = requests.get(url) response.raise_for_status() choice = response.json() hits = choice.get('hits') if hits: for idx, hit in enumerate(hits, 1): print(f"\nRecipe {idx}:") pprint(hit['recipe']['ingredientLines']) else: print("No ingredients found. Please try a different recipe.")
关于示例代码的疑问
你参考的示例能直接用字符串索引,大概率是示例针对的是单个结果的场景(比如API返回的hits被处理成了单个字典),但Edamam的标准搜索API返回中,hits始终是列表结构,所以必须先处理列表再访问内部的字典字段。
内容的提问来源于stack exchange,提问作者Sophie Milward
相关产品推荐
相关产品推荐

