pythonpython-3.xsetlist-comprehensionset-comprehension

Get single "set" object from the list values present in the dictionary


I'm trying to build a set from the values of a dictionary. Each dictionary value is a list of strings.

{'a': ['a','b','c'],'b':['a','b','d'],...}

I am trying to use .update(x) to concatenate a set containing values from the dictionary. I already have success with a standard for-loop:

ingredientSet = set()
for values in recipes.values():
    ingredientSet.update(values)

What I would like to do, if possible, is to do this in a set comprehension. So far I have this:

ingredientSet = { ingredientSet.update(x) for x in recipes.values() }

but my IDE is giving me an error that "ingredientSet" is referenced before its assignment.

Is it possible to use .update(x) in the comprehension, or is there another way to concatenate the items into the set in a comprehension?


Solution

  • If you want a comprehension you can do that with two fors like:

    Code:

    values_set = {item for items in data.values() for item in items}
    

    Test Code:

    data = {'a': ['a','b','c'],'b':['a','b','d']}
    
    values_set = {item for items in data.values() for item in items}
    print(values_set)
    

    Result:

    {'d', 'b', 'c', 'a'}