擅长:python、mysql、java
<p>对于你提到的案例,很简单:</p>
<pre><code>d = {}
for word in words:
d[word[0]] = word
</code></pre>
<p>当然,一般的注意事项也适用(dict没有被排序,因此不涉及过滤,如果<code>"Adam"</code>和{<cd2>}都在输入中,只有第二个将进入输出,等等)。为了解决后一个问题,您可能需要考虑一个<code>collections.defaultdict</code>:</p>
^{pr2}$
<p>这将给您留下映射到列表的字符的dict。而且,一旦你有了这个,如果你真的想让它按键“排序”,你可以用<code>collections.OrderedDict</code>在这之后:</p>
<pre><code>odict = OrderedDict()
for key in sorted(d): # d is the defaultdict from the last step.
odict[key] = d[key]
</code></pre>