Python 根据值对字典键进行排序
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4690094/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Sorting dictionary keys based on their values
提问by PDStat
I have a python dictionary setup like so
我有一个像这样的python字典设置
mydict = { 'a1': ['g',6],
'a2': ['e',2],
'a3': ['h',3],
'a4': ['s',2],
'a5': ['j',9],
'a6': ['y',7] }
I need to write a function which returns the ordered keys in a list, depending on which column your sorting on so for example if we're sorting on mydict[key][1] (ascending)
我需要编写一个函数来返回列表中的有序键,这取决于您排序的列,例如,如果我们在 mydict[key][1](升序)上排序
I should receive a list back like so
我应该像这样收到一份清单
['a2', 'a4', 'a3', 'a1', 'a6', 'a5']
It mostly works, apart from when you have columns of the same value for multiple keys, eg. 'a2': ['e',2] and 'a4': ['s',2]. In this instance it returns the list like so
除了当您有多个键的相同值的列时,它通常有效,例如。'a2': ['e',2] 和 'a4': ['s',2]。在这种情况下,它像这样返回列表
['a4', 'a4', 'a3', 'a1', 'a6', 'a5']
Here's the function I've defined
这是我定义的函数
def itlist(table_dict,column_nb,order="A"):
try:
keys = table_dict.keys()
values = [i[column_nb-1] for i in table_dict.values()]
combo = zip(values,keys)
valkeys = dict(combo)
sortedCols = sorted(values) if order=="A" else sorted(values,reverse=True)
sortedKeys = [valkeys[i] for i in sortedCols]
except (KeyError, IndexError), e:
pass
return sortedKeys
And if I want to sort on the numbers column for example it is called like so
如果我想对数字列进行排序,例如它是这样调用的
sortedkeysasc = itmethods.itlist(table,2)
So any suggestions?
那么有什么建议吗?
Paul
保罗
采纳答案by Sven Marnach
Wouldn't it be much easier to use
使用起来会不会容易很多
sorted(d, key=lambda k: d[k][1])
(with dbeing the dictionary)?
(d作为字典)?
回答by ulidtko
>>> L = sorted(d.items(), key=lambda (k, v): v[1])
>>> L
[('a2', ['e', 2]), ('a4', ['s', 2]), ('a3', ['h', 3]), ('a1', ['g', 6]), ('a6', ['y', 7]), ('a5', ['j', 9])]
>>> map(lambda (k,v): k, L)
['a2', 'a4', 'a3', 'a1', 'a6', 'a5']
Here you sort the dictionary items (key-value pairs) using a key- callable which establishes a total order on the items.
在这里,您使用键对字典项(键值对)进行排序- 可调用,它在项上建立总顺序。
Then, you just filter out needed values using a mapwith a lambdawhich just selects the key. So you get the needed list of keys.
然后,您只需使用 a 过滤掉所需的值map, alambda只选择键。因此,您将获得所需的密钥列表。
EDIT:see this answerfor a much better solution.
编辑:请参阅此答案以获得更好的解决方案。
回答by Amber
def itlist(table_dict, col, desc=False):
return [key for (key,val) in
sorted(
table_dict.iteritems(),
key=lambda x:x[1][col-1],
reverese=desc,
)
]
回答by Kimvais
Although there are multiple working answers above, a slight variation / combination of them is the most pythonicto me:
尽管上面有多个有效的答案,但它们的细微变化/组合对我来说是最pythonic的:
[k for (k,v) in sorted(mydict.items(), key=lambda (k, v): v[1])]
回答by John La Rooy
>>> mydict = { 'a1': ['g',6],
... 'a2': ['e',2],
... 'a3': ['h',3],
... 'a4': ['s',2],
... 'a5': ['j',9],
... 'a6': ['y',7] }
>>> sorted(mydict, key=lambda k:mydict[k][1])
['a2', 'a4', 'a3', 'a1', 'a6', 'a5']
>>> sorted(mydict, key=lambda k:mydict[k][0])
['a2', 'a1', 'a3', 'a5', 'a4', 'a6']

