Python案例怎么按值排序字典?

wen python案例 68

本文目录导读:

Python案例怎么按值排序字典?

  1. 方法1:使用 sorted() 和 lambda 表达式
  2. 方法2:使用 itemgetter
  3. 方法3:包含多个键值对或复杂值
  4. 方法4:处理字符串值
  5. 完整示例:按词频排序

在Python中,有多种方法可以按值对字典进行排序,这里提供几个常见的案例:

方法1:使用 sorted() 和 lambda 表达式

# 示例字典
scores = {'张三': 85, '李四': 92, '王五': 78, '赵六': 95}
# 按值升序排序(从低到高)
sorted_asc = dict(sorted(scores.items(), key=lambda x: x[1]))
print("升序排序:", sorted_asc)
# 输出: {'王五': 78, '张三': 85, '李四': 92, '赵六': 95}
# 按值降序排序(从高到低)
sorted_desc = dict(sorted(scores.items(), key=lambda x: x[1], reverse=True))
print("降序排序:", sorted_desc)
# 输出: {'赵六': 95, '李四': 92, '张三': 85, '王五': 78}

方法2:使用 itemgetter

from operator import itemgetter
scores = {'张三': 85, '李四': 92, '王五': 78, '赵六': 95}
# 按值升序排序
sorted_asc = dict(sorted(scores.items(), key=itemgetter(1)))
print("升序排序:", sorted_asc)
# 按值降序排序
sorted_desc = dict(sorted(scores.items(), key=itemgetter(1), reverse=True))
print("降序排序:", sorted_desc)

方法3:包含多个键值对或复杂值

# 字典包含复杂值
students = {
    '张三': {'age': 20, 'score': 85},
    '李四': {'age': 22, 'score': 92},
    '王五': {'age': 19, 'score': 78}
}
# 按分数的值排序
sorted_by_score = dict(sorted(students.items(), key=lambda x: x[1]['score']))
print("按分数排序:", sorted_by_score)
# 按年龄的值排序(降序)
sorted_by_age = dict(sorted(students.items(), key=lambda x: x[1]['age'], reverse=True))
print("按年龄降序排序:", sorted_by_age)

方法4:处理字符串值

# 字符串作为值
city_population = {
    '北京': '2154万',
    '上海': '2428万',
    '广州': '1868万',
    '深圳': '1768万'
}
# 如果字符串值可以转换,按数值排序
sorted_cities = dict(sorted(city_population.items(), 
                          key=lambda x: int(x[1].replace('万', '')), 
                          reverse=True))
print("按人口降序排序:", sorted_cities)
# 输出: {'上海': '2428万', '北京': '2154万', '广州': '1868万', '深圳': '1768万'}

完整示例:按词频排序

# 单词出现频率统计
text = "apple banana apple orange banana apple"
word_count = {}
for word in text.split():
    word_count[word] = word_count.get(word, 0) + 1
print("原字典:", word_count)
# 按出现频率降序排序
sorted_words = dict(sorted(word_count.items(), 
                         key=lambda x: x[1], 
                         reverse=True))
print("按频率降序排序:", sorted_words)

关键点:

  1. sorted() 函数返回排序后的键值对列表
  2. 使用 dict() 转换为字典
  3. key=lambda x: x[1] 表示按值排序
  4. reverse=True 实现降序排序
  5. 在 Python 3.7+ 中,字典会保持插入顺序

抱歉,评论功能暂时关闭!