identify a set containing correct values in dictionary of sets
<p>I have a dictionary of sets, and two values to test. I need to identify the set containing both values (there's only one correct set) and return the key of that set. I thought I could get away with a one-liner like that below, but no success this far. </p>

<pre><code>d = {"set1": {"A", "B", "C"}, "set2": {"D", "E", "F"}, "set3":{"A", "D", "C"}}
value1 = "A"
value2 = "B"

def do_values_belong_in_same_set(value1, value2):
    if all(x in v for k, v in d.items() for x in [value1, value2]) is True:
        return True, k
    else:
        return False
</code></pre>

<p>The desired output here would be: True, "set1"</p>

<p>The "v for k, v in d.items()" part doesn't do the trick. Nor does simpler "x in d.values()" What would work? Or will I just need to construct a proper for-loop for this? Thanks for your help!</p>

<p>You can use <a href="https://docs.python.org/3/library/stdtypes.html#set.issubset" rel="nofollow"><code>set.issubset</code></a> (which uses the <code>&lt;=</code> operator) by combining your needle characters into a set.</p>

<pre><code>d = {"set1": {"A", "B", "C"}, "set2": {"D", "E", "F"}, "set3":{"A", "D", "C"}}
value1 = "A"
value2 = "B"

needle_set = set([value1, value2])
result = next(k for k,v in d.items() if needle_set.issubset(v))
# or needle_set &lt;= v, or v &gt;= needle_set, or
# v.issuperset(needle_set), all are the same condition
</code></pre>

<p>You could roll it into a function with your requested output like:</p>

<pre><code>def do_values_belong_in_same_set(source_d, *values):
    # I use the variadic argument `value` here so you can check any number of values
    # and include the source dict by name as best practice
    needle_set = set(values)
    result = next(k for k,v in source_d.items() if needle_set &lt;= v)
    if result:
        return True, result
    else:
        return False
</code></pre>

python python-3.x