python - 按值和字典序对字典进行排序

标签 python sorting

<分区>

我有一本字典:{'a':10,'b':20,'c':5,'d':5,'e':5} 并想得到它

    b 20
    a 10
    c 5
    d 5
    e 5

按值排序,如果我按值相等 - 它必须按字典顺序排序。

注意:使用python 2

最佳答案

为了匹配您想要的实际输出,您必须使用两个键来排序,用 - 否定 int 值:

d = {'a':10,'b':20,'c':5,'d':5,'e':5}

for k,v in sorted(d.items(),key=lambda x:(-x[1],x[0])):
    print("{} {}".format(k,v))

输出:

b 20
a 10
c 5
d 5
e 5

关于python - 按值和字典序对字典进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28839182/

相关文章:

c - 对字符数组进行冒泡排序

c# - 在 C# Ilist 中排队

python - 将脚本从 Powershell 转换为 Python-Regex 未按预期工作

mysql - 查找具有相同商品编号的每组行的最低价格条目的详细信息

python - 以类似枢轴的样式重新格式化数据框

python - 高阶函数(映射)

python - Unix 排序产生错误的输出

javascript - 如何修改虚线单元格名称的排序代码?

python - Microsoft Outlook 图形事件 API : how to get different timezone?

python - 将 json 转换为 x-www-form-urlencoded