Ati*_*ooq 4 python sorting python-3.7
我有一个由(名称,值)对组成的python字典,像这样
pyDictionary = {"Bob":12,"Mellissa":12,"roger":13}
Run Code Online (Sandbox Code Playgroud)
我想做的就是获得上述字典的排序版本,在该排序中,首先对值赋予第一个属性,然后进行排序,如果两对值相同,则应通过字典比较这些名称来进行比较。
我如何在python3.7中实现呢?
您可以sorted
与一起使用key
,并OrderedDict
从结果构建一个以维护订单。
(最后一步仅适用于python 3.6 <
,在python 3.7中,字典按其键插入时间排序)
from collections import OrderedDict
d = {"Mellissa":12, "roger":13, "Bob":12}
OrderedDict(sorted(d.items(), key=lambda x: (x[1], x[0])))
# dict(sorted(d.items(), key=lambda x: (x[1], x[0]))) # for Python 3.7
# [('Bob', 12), ('Mellissa', 12), ('roger', 13)]
Run Code Online (Sandbox Code Playgroud)
或者,您也可以使用operator.itemgetter
直接分别从每个元组获取value
和key
:
OrderedDict(sorted(d.items(), key=itemgetter(1,0)))
# dict(sorted(d.items(), key=itemgetter(1,0))) # python 3.7
# [('Bob', 12), ('Mellissa', 12), ('roger', 13)]
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
133 次 |
最近记录: |