按字母排序字典键,然后按字母顺序排列具有相同值的字典 [英] Sorting dictionary keys by value, then those with the same value alphabetically

查看:251
本文介绍了按字母排序字典键,然后按字母顺序排列具有相同值的字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道这个标题没有很好的解释,所以我会尝试在这里做一个更好的工作。我想通过各自的值对字典的键进行排序,然后按字母顺序排列具有相同值的任何键。什么是最好的方式来做到这一点,理想情况下没有使用模块?

I know it wasn't well explained in the title so I'll try and do a better job here. I want to sort a dictionary's keys by their respective values, and then sort any keys with the same value alphabetically. What is the best way to do this, ideally without the use of modules?

python会自动执行以下类型:

Does python do this automatically with a sort like:

sorted(dictionary.items(), key=lambda x: x[1])

代码,它似乎工作,但我不知道是否只是巧合。我在文档中找不到任何东西,我需要知道它是否会一直工作。

I tried the above code and it seemed to work but I couldn't tell if it was just coincidence or not. I couldn't find anything in the docs and I need to know if it will always work.

开始字典:

dictionary = {'d':2, 'c':1, 'a':2, 'b':3}

按值排序:

['c', 'd', 'a', 'b']

(1,2,2,3 )

按字母顺序排列相同值的项目:

Items with the same value sorted alphabetically:

['c', 'a', 'd', 'b']

(1,2,2 ,3)

推荐答案

我想你想要的:

sorted(dictionary.items(), key=lambda t: t[::-1])

与以下相同:

def reverse_tuple(t):
    return t[::-1]

sorted(dictionary.items(), key=reverse_tuple)

这是因为元组按照字典排序排序。比较第一个元素,如果这些相等,python移动到第二个等等。

This works because tuples are sorted lexicographically. The first element is compared, if those are equal, python moves on to the second and so forth.

这几乎只是 sorted(dictionary)。 items())不幸的是,您的主排序顺序由元组中的第一个元素(即键)决定,而不是您想要的。诀窍是只是扭转元组,然后比较就像你想要的那样工作。

This is almost just sorted(dictionary.items()) unfortunately, then your primary sort order is determined by the first element in the tuples (i.e. the key) which isn't what you want. The trick is to just reverse the tuples and then the comparison works as you want it to.

这篇关于按字母排序字典键,然后按字母顺序排列具有相同值的字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆