在python中按字母降序排序字典值

2024-04-29 06:10:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我有个d法庭:在

higharr = {'Alex':2,
           'Steve':3,
           'Andy':4,
           'Wallace':6,
           'Andy':3,
           'Andy':5,
           'Dan':1,
           'Dan':0,
           'Steve':3,
           'Steve':8}

for score in sorted(higharr.values(), reverse=True):
    print (score)

我想打印出这些值按字母降序排列的键。下降部分正在工作,但我不确定如何在它的左侧添加相应的键。在

谢谢你


Tags: intrueforreversestevescorevaluessorted
3条回答

这就是你要找的吗?在

for key, score in sorted(higharr.values(), reverse=True):
    print (key, score)

首先,对于字典中的哪些条目是“键”,哪些是“值”,可能会有点混乱。在Python中,字典是由键值对组成的{键:值}. 因此,在higharr中,键是名称,值是 名字的权利。在

正如其他人所提到的,higharr可能无法完全按照您的预期工作,因为字典的键(名称)不是唯一的:

>>> 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}

如您所见,您添加的后面的键值对将覆盖前面的键值对。 也就是说,你可以在字典中将所有的唯一键进行排序和打印,如下所示:

^{pr2}$

如果您想按字母降序对键进行排序,则基本上可以执行相同的操作:

>>> 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)

您可以使用其他数据结构,因为您有重复的键。 但一般来说,您可能会考虑:

from operator import itemgetter
for i in sorted(higharr.items(), key=itemgetter(1), reverse=True):
    print i

相关问题 更多 >