Python 3 按其值对 dict 进行排序
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20944483/
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
Python 3 sort a dict by its values
提问by
The only methods I found work for python2 or return only list of tuples.
我发现的唯一方法适用于 python2 或只返回元组列表。
Is it possible to sort dictionary, e.g. {"aa": 3, "bb": 4, "cc": 2, "dd": 1}, by its values?
是否可以对字典进行排序,例如{"aa": 3, "bb": 4, "cc": 2, "dd": 1},按其值?
Order of sorted dictionary I want to achieve is from largest to smallest. I want results to look like this:
我想要实现的排序字典的顺序是从大到小。我希望结果如下所示:
bb 4
aa 3
cc 2
dd 1
And after sorting I want to store it into a text file.
排序后我想将它存储到一个文本文件中。
采纳答案by SzieberthAdam
itemgetter(see other answers) is (as I know) more efficient for large dictionaries but for the common case, I believe that d.getwins. And it does not require an extra import.
itemgetter(请参阅其他答案)(据我所知)对于大型词典更有效,但对于常见情况,我相信它会d.get获胜。而且它不需要额外的import.
>>> d = {"aa": 3, "bb": 4, "cc": 2, "dd": 1}
>>> for k in sorted(d, key=d.get, reverse=True):
... k, d[k]
...
('bb', 4)
('aa', 3)
('cc', 2)
('dd', 1)
Note that alternatively you can set d.__getitem__as keyfunction which may provide a small performance boost over d.get.
请注意,或者您可以设置d.__getitem__askey函数,这可能会在d.get.
回答by Andrew Gorcester
To sort a dictionary and keep it functioning as a dictionary afterwards, you could use OrderedDictfrom the standard library.
要对字典进行排序并在之后保持它作为字典的功能,您可以使用标准库中的OrderedDict。
If that's not what you need, then I encourage you to reconsider the sort functions that leave you with a list of tuples. What output did you want, if not an ordered list of key-value pairs (tuples)?
如果这不是您所需要的,那么我鼓励您重新考虑给您留下元组列表的排序函数。如果不是键值对(元组)的有序列表,您想要什么输出?
回答by Paul Draper
from collections import OrderedDict
from operator import itemgetter
d = {"aa": 3, "bb": 4, "cc": 2, "dd": 1}
print(OrderedDict(sorted(d.items(), key = itemgetter(1), reverse = True)))
prints
印刷
OrderedDict([('bb', 4), ('aa', 3), ('cc', 2), ('dd', 1)])
Though from your last sentence, it appears that a list of tuples would work just fine, e.g.
虽然从你的最后一句话来看,元组列表似乎可以正常工作,例如
from operator import itemgetter
d = {"aa": 3, "bb": 4, "cc": 2, "dd": 1}
for key, value in sorted(d.items(), key = itemgetter(1), reverse = True):
print(key, value)
which prints
哪个打印
bb 4
aa 3
cc 2
dd 1
回答by Reck
To sort dictionary, we could make use of operator module. Hereis the operator module documentation.
要对字典进行排序,我们可以使用 operator 模块。这是操作员模块文档。
import operator #Importing operator module
dc = {"aa": 3, "bb": 4, "cc": 2, "dd": 1} #Dictionary to be sorted
dc_sort = sorted(dc.items(),key = operator.itemgetter(1),reverse = True)
print dc_sort
Output sequence will be a sorted list :
输出序列将是一个排序列表:
[('bb', 4), ('aa', 3), ('cc', 2), ('dd', 1)]
If we want to sort with respect to keys, we can make use of
如果我们想根据键进行排序,我们可以利用
dc_sort = sorted(dc.items(),key = operator.itemgetter(0),reverse = True)
Output sequence will be :
输出序列将是:
[('dd', 1), ('cc', 2), ('bb', 4), ('aa', 3)]
回答by Bede Constantinides
A simpler (and ~10% faster) way is to use a lambda expression
一种更简单(且速度约 10%)的方法是使用 lambda 表达式
d = {'aa': 3, 'bb': 4, 'cc': 2, 'dd': 1}
s = sorted(d.items(), key=lambda x: x[1], reverse=True)
for k, v in s:
print(k, v)
Timings
时间安排
%%timeiton CPython 3.7 with print(k, v)substituted for passto keep IO out of the picture.
%%timeit在 CPython 3.7 上print(k, v)用 for 代替pass以将 IO 排除在外。
Accepted answer using d.get():
使用 d.get() 接受的答案:
1.19 μs ± 16.3 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
Lambda expression:
拉姆达表达式:
1.07 μs ± 10.7 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
回答by Boris
You can sort by valuesin reverseorder (largest to smallest) using a dictionary comprehension:
您可以使用字典理解按相反的顺序(从大到小)对值进行排序:
{k: d[k] for k in sorted(d, key=d.get, reverse=True)}
# {'b': 4, 'a': 3, 'c': 2, 'd': 1}
If you want to sort by valuesin ascending order (smallest to largest)
如果要按升序(从小到大)按值排序
{k: d[k] for k in sorted(d, key=d.get)}
# {'d': 1, 'c': 2, 'a': 3, 'b': 4}
If you want to sort by the keysin ascending order
如果要按键升序排序
{k: d[k] for k in sorted(d)}
# {'a': 3, 'b': 4, 'c': 2, 'd': 1}
This works on CPython 3.6+ and any implementation of Python 3.7+ because dictionaries keep insertion order.
这适用于 CPython 3.6+ 和 Python 3.7+ 的任何实现,因为字典保持插入顺序。

