如何打印字典中某个值的多个索引?

Ell*_*lly 1 python indexing dictionary

我刚刚学习 python,我遇到了一个问题。如何打印字典中某个值的多个索引?gender_ids特别是,我想打印作为键的dictionary_title数组的每个元素的索引。

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}}

Run Code Online (Sandbox Code Playgroud)

这是我的代码:

   for values in dictionary_title["genre_ids"]: 
   for item in values:       
       if item == 28:      
           print(values.index(item))  
Run Code Online (Sandbox Code Playgroud)

例如,我想打印index:2,6,8,10,11,它们是带有键genre_ids=28的项目的索引。我该怎么做?

hev*_*ev1 6

您可以将列表理解与 一起使用enumerate

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}]

res = [i for i, o in enumerate(dictionary_title) if o['genre_ids'] == 28]
print(res)
Run Code Online (Sandbox Code Playgroud)