0

I got this list of strings:

json = ['red', 'blue', 'green']

and this constant list of Colors:

MY_COLORS = [Color('blue', 'www.example.com'), Color('red', 'www.example2.com')]

class Color:
    def __init__(self, name: str, url: str):
        self.name = name
        self.url = url

Now I want to check if there is any object within my constant list with a name value that matches any string of my list of strings. If so I want to return all the matching objects as list to get this result:

some_magic(MY_COLORS, json) == [objectred, objectblue]
# no object with name green as its not inside my "MY_COLORS" constant

I tried "any" like suggested in Check if List of Objects contain an object with a certain attribute value but that did not solve the problem oof returning a list of all matching objects.

jwodder
  • 54,758
  • 12
  • 108
  • 124
HelloWorld0815
  • 610
  • 4
  • 11
  • 29

2 Answers2

3

You could do:

class Color:
    def __init__(self, name: str, url: str):
        self.name = name
        self.url = url

MY_COLORS = [Color('blue', 'www.example.com'), Color('red', 'www.example2.com')]

json = ['red', 'blue', 'green']
set_json = set(json)

result = [color for color in  MY_COLORS if color.name in set_json]
print(result)
Dani Mesejo
  • 61,499
  • 6
  • 49
  • 76
0

len([color for color in MY_COLORS if color.name in json]) == 0 It returns True if a color name match one of the color listed in the json variable, False otherwise.

Louis Saglio
  • 1,120
  • 10
  • 20