如何在Python字典数组中打印特定genre_ids值的多个索引?
如何在字典数组中筛选genre_ids值为28的元素索引?
我是Python初学者,想要在字典数组dictionary_title中,打印所有genre_ids值为28的元素的索引,期望输出索引2、6、8、10、11,但当前代码无法实现。
相关数据:
dictionary_title=[ {'label': 'Green', 'genre_ids': 878}, {'label': 'Pink', 'genre_ids': 16}, {'label': 'Orange', 'genre_ids': 28}, {'label': 'Yellow', 'genre_ids': 9648}, {'label': 'Red', 'genre_ids': 878}, {'label': 'Brown', 'genre_ids': 12}, {'label': 'Black', 'genre_ids': 28}, {'label': 'White', 'genre_ids': 14}, {'label': 'Blue', 'genre_ids': 28}, {'label': 'Light Blue', 'genre_ids': 10751}, {'label': 'Magenta', 'genre_ids': 28}, {'label': 'Gray', 'genre_ids': 28} ]
我的错误代码:
for values in dictionary_title["genre_ids"]: for item in values: if item == 28: print(values.index(item))
代码问题分析
你的代码存在两个核心错误:
dictionary_title是列表类型,无法直接通过dictionary_title["genre_ids"]访问,这会直接抛出KeyError。- 遍历逻辑完全错误:你没有获取列表元素的索引,反而尝试在字典的键集合中查找数值28,逻辑与需求不符。
修正方案
方案一:使用enumerate遍历获取索引
enumerate可以同时返回列表的索引和对应元素,只需判断每个字典的genre_ids值即可:
for idx, item in enumerate(dictionary_title): if item['genre_ids'] == 28: print(idx)
方案二:列表推导式收集索引(推荐)
如果需要后续复用这些索引,可以先收集到列表中再输出:
target_indices = [idx for idx, item in enumerate(dictionary_title) if item['genre_ids'] == 28] print(target_indices) # 输出: [2, 6, 8, 10, 11]
内容的提问来源于stack exchange,提问作者Elly
相关产品推荐
相关产品推荐

