首先,有可能会有点混乱,以在你的字典哪些条目是“钥匙”,哪些是“价值观”。在Python中,字典由{key:value}通过键值对形成。因此,在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}
正如你所看到的,后来键值对你添加将覆盖更早的。 话虽这么说,您可以排序并打印在字典中对将作为您以下要求所有独特的键:
>>> for entry in sorted(higharr.items(), key = lambda x: x[1], reverse=True)
... print(entry)
...
('Steve', 8)
('Wallace', 6)
('Andy', 5)
('Alex', 2)
('Dan', 0)
相反,如果你想通过降序字母顺序排列的按键排序,你基本上可以做到同样的事情:
>>> 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)
看看什么higharr.keys()做什么。然后排序该列表,并按照该顺序询问这些键的字典?...... – 2014-11-23 20:27:06
您不能拥有这本词典 - 您的键不是唯一的。尝试打印higharr。你可能会发现你缺少条目。 – 2014-11-23 20:28:23
你说“按字母顺序降序”,但你正在按数值排序。你想要什么命令? – iCodez 2014-11-23 20:29:19