Search code examples
pythonlistdictionary

Extracting several values out from a list in Python


I had a dictionary that I transformed into a list, and my task is to create product lists based on their tags. However I keep getting an empty list:

That's my list (values_list):

[['lipstick', 'spray', 'polish', 'other'],
 [{'annotated_regions': [{'tags': ['lipstick'],
     'region_type': 'Box',
     'region': {'xmin': 0.6413427734375,
      'ymin': 0.2342342380079588015,
      'xmax': 0.234234230703125,
      'ymax': 0.4645647705992509}},
    {'tags': ['polish'],
     'region_type': 'Box',
     'region': {'xmin': 0.234234334375,
      'ymin': 0.234234224531835,
      'xmax': 0.4564560546875,
      'ymax': 0.2342341481741573}},
    {'tags': ['lipstick'],
     'region_type': 'Box'

My for loop:

lipstick_tag = []
for idx, item in enumerate(values_list):
    if 'tags' == 'lipstick':
        lipstick_tag.append(item)

Solution

  • Your for loop is expecting the data to be in a very different format from your values_list. Try this instead

    [item for item in values_list[1][0]['annotated_regions'] if 'lipstick' in item['tags']]