python字典根据value排序

时间:2022-07-25
本文章向大家介绍python字典根据value排序,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

有时候我们将数据保存在字典中,想将元素出现的次数按照顺序排序。我们可以考虑用lambda和sort函数实现。

比如以下数组:

from collections import Counter
words = ["i", "love", "i", "leetcode", "coding"]
print(c)

统计结果c为: Counter({'i': 2, 'love': 1, 'leetcode': 1, 'coding': 1})

我们想按照出现次数升序排列的话:

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

返回: [('love', 1), ('leetcode', 1), ('coding', 1), ('i', 2)]

对于相同的次数的元素,按照key的字母顺序排序:

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

降序:

sorted(c.items(), key=lambda x: (x[1], x[0]), reverse = True)

欢迎关注!