Sorting dictionary keys by value, then those with the same value alphabetically

拥有回忆 提交于 2020-01-24 16:17:40

问题


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?

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.

Starting dictionary:

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

Sorted by value:

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

(1, 2, 2, 3)

Items with the same value sorted alphabetically:

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

(1, 2, 2, 3)


回答1:


I think that you want:

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

which is the same as:

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

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

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.

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.



来源:https://stackoverflow.com/questions/28356342/sorting-dictionary-keys-by-value-then-those-with-the-same-value-alphabetically

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!