2

I want to join multiple sets that are obtained from instances of a class. Below is an example of what I am working with and what I tried. Changing the class is not an option.

class Salad:
   def __init__(self, dressing, veggies, others):
      self.dressing = dressing
      self.veggies = veggies
      self.others = others

SALADS = {
   'cesar'  : Salad('cesar',  {'lettuce', 'tomato'},  {'chicken', 'cheese'}),
   'taco'   : Salad('salsa',  {'lettuce'},            {'cheese', 'chili', 'nachos'})
}

I want OTHER_INGREDIENTS to be {'chicken', 'cheese', 'chili', 'nachos'}. So I tried:

OTHER_INGREDIENTS = sum((salad.others for salad in SALADS.values()), set())

That gives me an error "unsupported operand type(s) for +: 'set' and 'set' though. How do I do this?

I would prefer to use Python 2.7 without additional imports if possible.

2 Answers 2

7

You can use a set comprehension:

OTHER_INGREDIENTS = {
    element
    for salad in SALADS.values()
    for element in salad.others
}
Sign up to request clarification or add additional context in comments.

Comments

6

You can use the function union from set:

OTHER_INGREDIENTS = set().union(*(salad.others for salad in SALADS.values()))

Output

{'chili', 'cheese', 'chicken', 'nachos'}

2 Comments

Thanks, this worked and, while the other answer worked too, this one had the format that best matched our repo.
Glad I could help!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.