排序我有一个Python字典,看起来是这样的:建设字典值的列表,通过关键
attributes = {
'size': ['s','m','l'],
'color': ['black', 'orange'],
}
我想要得到值的列表。如果我使用values()
,我得到这个:
>>> attributes.values()
[['black', 'orange'], ['s', 'm', 'l']]
不过,我希望得到的名单列表,通过以相反的顺序字典键进行排序 - 即大小,然后颜色,没有颜色,然后大小。我想这一点:
[['s', 'm', 'l'], ['black', 'orange']]
我不necesarilly知道字典键是什么事前,但我总是知道如果我想他们按字母顺序或反向字母顺序。
有没有一些pythonic的方式来做到这一点?
我能想到的唯一的事情好像......不是很蟒蛇般:
keys = sorted(attributes.keys(), reverse=True)
result = []
for key in keys:
result.append(attributes[key])
很难从attributes.values()
去所有的,只是对列表进行排序!
字典是无序的,所以没有简单的方法来指定y字典键的显示顺序。您可以订购显示器,但不是字典本身。但是,您可以尝试使用Ordered Dict(包含在Python 2.7+中)来解决此问题。 –
'sorted(attributes,reverse = True)',你不需要.keys –