<p>为了验证<code>fridge</code>变量,您可以遵循以下示例:</p>
<pre><code>fridge = {"cheese":10, "milk":11, "feta":12, "cream":21, "onion":32, "pepper":14}
def fridge_validation (fridge = {}):
# Test if fridge is a dict type
if not isinstance(fridge, dict):
# if fridge isn't a dict type, throw an exception
raise TypeError("require a valid dictionary to be submitted!")
# if fridge is a dict type return it. So you got your validation
else:
return fridge
validation = fridge_validation(fridge)
print(validation)
</code></pre>
<p>输出:</p>
<pre><code>{'milk': 11, 'feta': 12, 'onion': 32, 'cheese': 10, 'pepper': 14, 'cream': 21}
</code></pre>
<p>然而,<code>{"cheese", "milk", "eggs"}</code>是<code>set type</code>而不是<code>dict type</code>。你知道吗</p>
<p>您可以使用<code>Python interpreter</code>进行验证:</p>
<pre><code>>> a = {"cheese", "milk", "eggs"}
>> type(a)
<class 'set'>
</code></pre>
<p>如您所见,<code>{"cheese", "milk", "eggs"}</code>是<code>set</code>而不是<code>dict</code>。因此,如果将其传递到<code>fridge_validation()</code>中,代码将抛出一个异常。你知道吗</p>
<p>另外,在您的方法中:</p>
<pre><code>def dummy(fridge):
fridge = {}
return fridge
</code></pre>
<p>返回值总是等于<code>{}</code>,这是一个空的<code>dict type</code>原因是您的代码总是用一个空的dict覆盖您的冰箱值</p>
<p>第二个问题的答案。你知道吗</p>
<p>你怎么能从你的字典中减去值呢?答案很简单:</p>
<p>我想您在用<code>fridge_validation()</code>方法验证了dict之后得到了dict。例如:</p>
<pre><code>validation = {"cheese":10, "milk":11, "feta":12, "cream":21, "onion":32, "pepper":14}
</code></pre>
<p>所以:</p>
<pre><code>print(validation["cheese"])
</code></pre>
<p>输出:</p>
<pre><code>10
</code></pre>
<p>此外:</p>
<pre><code>print(validation["milk"])
</code></pre>
<p>输出:</p>
<pre><code>11
</code></pre>
<p>其他的就这样。总之,为了从dict中减去值,可以使用:<code>dictionary["key"]</code>这将输出键的值。你知道吗</p>
<p>另外,我建议您阅读本文<a href="https://www.tutorialspoint.com/python/python_dictionary.htm" rel="nofollow noreferrer">tutorial</a>,以了解如何处理<code>python dicts</code>。你知道吗</p>