排序字典值 - 降我有字母
的字典: -排序字典值 - 降我有字母
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)
我想打印出与该值下降的字母顺序是值的键。降序部分正在工作,但我不确定如何将相应的键添加到左侧。
谢谢
首先,有可能会有点混乱,以在你的字典哪些条目是“钥匙”,哪些是“价值观”。在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)
这真的有助于谢谢你 – baconstripsboss 2014-11-24 09:32:55
您可能会使用其他数据结构,因为您有重复的键。 但总的来说,你可能会考虑这一点:
from operator import itemgetter
for i in sorted(higharr.items(), key=itemgetter(1), reverse=True):
print i
非常好。干杯 – baconstripsboss 2014-11-24 13:29:57
这是你在找什么?
for key, score in sorted(higharr.values(), reverse=True):
print (key, score)
这也是工作。谢谢 – baconstripsboss 2014-11-24 13:30:20
你很近。枚举字典的项目和使用自定义排序关键字:
>>> for name, score in sorted(higharr.iteritems(), key=lambda item:item[1], reverse=True):
... print name, score
...
Steve 8
Wallace 6
Andy 5
Alex 2
Dan 0
>>>
优秀。谢谢 – baconstripsboss 2014-11-24 13:32:03
看看什么higharr.keys()做什么。然后排序该列表,并按照该顺序询问这些键的字典?...... – 2014-11-23 20:27:06
您不能拥有这本词典 - 您的键不是唯一的。尝试打印higharr。你可能会发现你缺少条目。 – 2014-11-23 20:28:23
你说“按字母顺序降序”,但你正在按数值排序。你想要什么命令? – iCodez 2014-11-23 20:29:19