擅长:python、mysql、java
<p>你这样编字典</p>
<pre><code> if ch in ascii_lowercase:
if ch not in data:
data[ch] = 1
else:
data[ch] += 1
</code></pre>
<p>所以我假设键是字符,值是字符的计数:</p>
<pre><code>{'a':867, 'b':233, ....}
</code></pre>
<p><a href="https://docs.python.org/3/library/stdtypes.html#dict.items" rel="nofollow noreferrer">^{<cd1>}</a>以元组的形式生成(键,值)对,就像<code>('a', 867)</code>。你知道吗</p>
<pre><code>def print_output(data):
for char in sorted(data.items()):
#print(char)
print(str(char), str(data[char]))
</code></pre>
<p>所以</em><code>for char in sorted(data.items()):</code>中的<code>char</code><em>是('a',867),您试图将它用作导致<a href="https://docs.python.org/3/library/exceptions.html#KeyError" rel="nofollow noreferrer">KeyError</a>的<code>str(data[char])</code>键。你知道吗</p>
<p>试试看</p>
<pre><code>def print_output(data):
for char, count in sorted(data.items()):
print(str(char), str(count))
</code></pre>
<p>或者</p>
<pre><code>def print_output(data):
for char in sorted(data):
print(str(char), str(data[char]))
</code></pre>