def main(): with open("input_sample.txt") as f: lines = f.read().split('\n') all_ingredients = set() all_allergens = set() may_contain = {} unsafe_ingredients = {} for line in lines: ingredients, contains = line.split(' (contains ') ingredients = ingredients.split(' ') contains = contains[:-1].split(', ') # remove trailing ")" then split all_ingredients = all_ingredients | set(ingredients) all_allergens = all_allergens | set(contains) if __name__ == "__main__": main()