i'm just learning python and i have a problem. how can i print multiple indexes of a certain value in a dictionary? In particular I want to print the index of each element of the dictionary_title array which has gender_ids as key.
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}}
This is my code:
for values in dictionary_title["genre_ids"]:
for item in values:
if item == 28:
print(values.index(item))
For example i want print index:2,6,8,10,11 which are the indexes of the items with the key genre_ids=28. How can i do?
CodePudding user response:
You can use a list comprehension with 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)
CodePudding user response:
"dictionary title" must be a list!!! I leave you the code of how to do it :-)
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 idx in range(0, len(dictionary_title)):
if dictionary_title[idx]["genre_ids"]==28:
print(idx)