How do I iterate through a dictionary's sets of values and return the key of the sets of values that matches a given set?
<p>I have a function guess which is supposed to return the key of the set of animal values (arg2) that matches the set of observations (arg1). For instance, if the set of observations = {'pet,' 'fluffy'} and the dictionary of animals = {'cat': {'pet,' 'fluffy', 'cute'}, 'dog': {'pet'}} then the function should return the key of cat because cat has all of the values and set elements that the set of observations has. Notice that cat also has extra values/elements that observations does not. Also notice that dog has one of the values that the set observations has - "pet" - however, dog doesn't have all of the values that the observations set has, and therefore, it isn't returned. </p>

<p>This is my function so far:</p>

<pre><code>def guess(observations, animals):

    for key, value in animals.items():
        if observations in value:
                 return key
</code></pre>

<p>This is a test:</p>

<pre><code>guess({'pet', 'fluffy'}, {'cat': {'pet', 'fluffy', 'cute'}, 'dog': {'pet'}})
</code></pre>

<p>So far, my function returns None when I want it to return cat. How do I see if my set of observations matches a set and/or subset of a set of animal values? My mind wants me to incorrectly believe that checking if the set of observations is in the set of values is the best way to compare sets. I've also tried iterating through my observations to see if they're in the set of values. This method works to an extent. However, when I try:</p>

<pre><code>for key, value in animals.items():
    for obs in observations:
        if obs in value:
            return key
</code></pre>

<p>It returns dog. I'd appreciate any help. Thanks</p>

<p>What you want to know is whether the value of each item in <code>animals</code> is a superset of <code>observations</code>. Thankfully, <code>set</code> has a <a href="https://docs.python.org/3/library/stdtypes.html#set.issuperset" rel="nofollow">method</a> to test exactly that, so your function is straightforward:</p>

<pre><code>def guess(observations, animals):
    return {k for k, v in animals.items() if v.issuperset(observations)}
</code></pre>

<p>Note that <code>guess()</code> returns a set, because there may be more than one item in <code>animals</code> that matches the criteria:</p>

<pre><code>&gt;&gt;&gt; animals = {'cat': {'pet,' 'fluffy', 'cute'}, 'dog': {'pet'}}
&gt;&gt;&gt; observations = {'pet,' 'fluffy'}
&gt;&gt;&gt; guess(observations, animals)
{'cat'}
</code></pre>

<p>It's also possible to use the <code>&gt;=</code> and <code>&lt;=</code> operators as synonyms of <code>issuperset</code> and <code>issubset</code> (not <code>&gt;</code> and <code>&lt;</code>, which are synonyms for <em>proper</em> supersets and subsets respectively).</p>

python python-3.x