#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
@file: interview02.py
@time: 2022/8/27 22:05
@desc:
"""
"""
- 常用的需求 对字典排序还算是一个比较常用的需求,比如说前端要求页面展示一下按人员的年龄倒序,这时候就会用的到了
- 字典 字典列表 键排序 值排序 正序 倒序
"""
# 按水果的价格由低到高或由高到低排序
dict = {'苹果': '2.5', '桔子': '5', '桃子': '2.8', '香蕉': '6'}
# print(dir(dict))
dict_new = sorted(dict.items(), key=lambda x: x[1])
print(dict_new)

print('==============================')
# 当然也可以倒排
dict_new = sorted(dict.items(), key=lambda x: x[1], reverse=True)
print(dict_new)

print('==============================')
# 可以按键排序
dict_new = sorted(dict.items(), key=lambda x: x[0])
print(dict_new)

print('==============================')
# 除了使用lambda函数外,还有其他的方法可以办到,比如operator
dict = {'苹果': '2.5', '桔子': '5', '桃子': '2.8', '香蕉': '6'}
dict_1 = sorted(dict.items(), key=operator.itemgetter(1)) # value
dict_2 = sorted(dict.items(), key=operator.itemgetter(0)) # value
dict_3 = sorted(dict.items(), key=operator.itemgetter(0), reverse=True) # value
print(dict_1)
print(dict_2)
print(dict_3)

print('==============================')
# 除了对字典排序,还可以对字典列表进行排序
list = [{'name': '苹果', 'price': '2.5'}, {'name': '桔子', 'price': '5'}, {'name': '香蕉', 'price': '6'}, {'name': '苹果', 'price': '3.5'}]
list1 = sorted(list, key=lambda x: x['name'])
list2 = sorted(list, key=lambda x: x['price'])
# list3 = sorted(list, key=lambda x: (x['name'], -x['price']))
list3 = sorted(list, key=lambda x: (x['name'], x['price']), reverse=True)
print(list1)
print(list2)
print(list3)
