<h2><code>setdefault(key[, default)</code></h2>
<p>来自<a href="https://docs.python.org/3/library/stdtypes.html#dict.setdefault" rel="nofollow noreferrer">the docs</a>:</p>
<blockquote>
<p>If <code>key</code> is in the dictionary, return its value. If not, insert <code>key</code> with a value of <code>default</code> and return <code>default</code>. <code>default</code> defaults to <code>None</code>.</p>
</blockquote>
<p><strong>用法示例</strong></p>
<pre><code>>>> d = {'a': 1, 'b': 2, 'c': 3}
>>> d.setdefault('a') # returns the corresponding value for key 'a'
1
>>> d.setdefault('a', 10) # returns the corresponding value for key 'a'
1
>>> d.setdefault('b') # returns the corresponding value for key 'b'
2
>>> d.setdefault('c', 100) # returns the corresponding value for key 'c'
3
>>> type(d.setdefault('z')) # because 'z' is not a key of d, None is returned which is the default value of default
<class 'NoneType'>
>>> d.setdefault('z', 666) # returns 666 since key 'z' is not in d
666
</code></pre>
<h3>在你的代码中</h3>
<p>我认为您很困惑,因为<code>curr = curr.setdefault(letter, {})</code>总是创建一个新的且<em>空的dict</em>,然后将其分配给<code>curr</code>。这意味着,不是重写值,而是为<code>words</code>中的每个元素在原始dict中添加嵌套级别。</p>
<p>我还认为,您希望用代码实现的是创建一个字典,将<code>words</code>中的每个元素都作为键,并将<code>{}</code>作为值,这样您就可以使用下面使用<em>dict comprehension</em>的代码来实现它:</p>
<pre><code>def what(*words):
return {word: {} for word in set(words)}
</code></pre>
<p><strong>注意:</strong>我添加了对<code>setdefault</code>的解释,因为您的问题已被特别针对本案例进行了查看,但我也想涵盖您的具体问题。</p>