Python中 字典排序问题
- 字典排序问题,大概能分为
- 根据value排序
- 列表 list 套 字典 dict时的排序
1.根据value排序
举个例子
prices = {
'AAPL': 191.88,
'GOOG': 1186.96,
'IBM': 149.24,
}
此时要求 按股票价格从高到低输出股票
则
res=dict(sorted(prices.items(),key=lambda kv:kv[1],reverse=True))
{'GOOG': 1186.96, 'AAPL': 191.88, 'IBM': 149.24}
- 这里将 字典prices 转化为可迭代对象 prices.items(),将键值对以元组的形式绑定。
即:
dict_items([('AAPL', 191.88), ('GOOG', 1186.96), ('IBM', 149.24)])
- 那么此时kv[0] 为key,kv[1]为对应的value
- 这里的reverse默认是False,升序排列。需要指定为True,降序排列。
列表 (list)套字典 (dict)时的排序
同样举例说明:
students = [
{'id': 1001, 'name': '周伟', 'sex': None, 'verbal': 90, 'math': 90, 'tel': '13512345670'},
{'id': 1002, 'name': '赵刚', 'sex': True, 'verbal': 56, 'math': 80, 'tel': '13512345678'},
{'id': 1003, 'name': '李强', 'sex': True, 'verbal': 48, 'math': 70, 'tel': '13512345680'},
{'id': 1004, 'name': '刘毅', 'sex': None, 'verbal': 92, 'math': 60, 'tel': '13512345688'},
{'id': 1005, 'name': '孙坚', 'sex': True, 'verbal': 85, 'math': 50, 'tel': '13512345698'},
{'id': 1006, 'name': '王小美', 'sex': False, 'verbal': 37, 'math': 40, 'tel': '13512345699'},
]
此时按照语文成绩 verbal 从大到小排列代码应为:
students.sort(key=lambda x: x['verbal'], reverse=True)
- 利用sort()函数排序,key指定依据verbal,这里的sort直接改变students顺序,无返回值
- 这里的reverse默认是False,升序排列。需要指定为True,降序排列。
- 结果为
{'id': 1004, 'name': '刘毅', 'sex': None, 'verbal': 92, 'math': 60, 'tel': '13512345688'}
{'id': 1001, 'name': '周伟', 'sex': None, 'verbal': 90, 'math': 90, 'tel': '13512345670'}
{'id': 1005, 'name': '孙坚', 'sex': True, 'verbal': 85, 'math': 50, 'tel': '13512345698'}
{'id': 1002, 'name': '赵刚', 'sex': True, 'verbal': 56, 'math': 80, 'tel': '13512345678'}
{'id': 1003, 'name': '李强', 'sex': True, 'verbal': 48, 'math': 70, 'tel': '13512345680'}
{'id': 1006, 'name': '王小美', 'sex': False, 'verbal': 37, 'math': 40, 'tel': '13512345699'}
非常感谢小伙伴们能看到这里,如果能还能点个赞,那就是对我最大的鼓励!