擅长:python、mysql、java
<p>首先,对于字典中的哪些条目是“键”,哪些是“值”,可能会有点混乱。在Python中,字典是由键值对组成的{键:值}. 因此,在higharr中,键是名称,值是
名字的权利。在</p>
<p>正如其他人所提到的,higharr可能无法完全按照您的预期工作,因为字典的键(名称)不是唯一的:</p>
<pre><code>>>> higharr = {'Alex':2,
'Steve':3,
'Andy':4,
'Wallace':6,
'Andy':3,
'Andy':5,
'Dan':1,
'Dan':0,
'Steve':3,
'Steve':8}
>>> higharr
{'Steve': 8, 'Alex': 2, 'Wallace': 6, 'Andy': 5, 'Dan': 0}
</code></pre>
<p>如您所见,您添加的后面的键值对将覆盖前面的键值对。
也就是说,你可以在字典中将所有的唯一键进行排序和打印,如下所示:</p>
^{pr2}$
<p>如果您想按字母降序对键进行排序,则基本上可以执行相同的操作:</p>
<pre><code>>>> for entry in sorted(higharr.items(), key=lambda x: x[0], reverse=True):
... print(entry)
...
('Wallace', 6)
('Steve', 8)
('Dan', 0)
('Andy', 5)
('Alex', 2)
</code></pre>