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 could slightly change the logic in your function to achieve this:</p>

<pre><code>def do_values_belong_in_same_set(value1, value2):
    r = next((k for k, v in d.items() if all(i in v for i in {value1, value2})), False)
    if r: 
        return True, r
    else: 
        return r
</code></pre>

<p>Calling <code>next</code> on the generator will return the first <code>k</code> (set name) if one exists and a default value of <code>False</code> is assigned if the value is not present. Then you return accordingly. </p>

<p>This yields the following results for different runs:</p>

<pre><code>do_values_belong_in_same_set(value1, value2)
(True, 'set1')

do_values_belong_in_same_set(value1, 'F')
False

do_values_belong_in_same_set(value1, 'E')
False

do_values_belong_in_same_set('F', 'E')
(True, 'set2')
</code></pre>

python python-3.x