方法一:
解析: 使用sorted 方法, 排序后的结果为一个元组. 可以字符串排序
1、按照键值(value)排序
a = {'a': 'China', 'c': 'USA', 'b': 'Russia', 'd': 'Canada'}
b = sorted(a.items(), key=lambda x: x[1], reverse=True)
# 结果:
# [('c', 'USA'), ('b', 'Russia'), ('a', 'China'), ('d', 'Canada')]
2、按照键名(key)排序
a = {'a': 'China', 'c': 'USA', 'b': 'Russia', 'd': 'Canada'}
b = sorted(a.items(), key=lambda x: x[0], reverse=True)
# [('d', 'Canada'), ('c', 'USA'), ('b', 'Russia'), ('a', 'China')]
3: 嵌套字典, 按照字典键名(key)排序
a = {
'a': {'b': 'China'},
'c': {'d': 'USA'},
'b': {'c': 'Russia'},
'd': {'a': 'Canada'}
}
b = sorted(a.items(), key=lambda x: x[1], reverse=True)
# [('c', {'d': 'USA'}), ('b', {'c': 'Russia'}), ('a', {'b': 'China'}), ('d', {'a': 'Canada'})]
4: 嵌套列表
# 针对列表第一个元素排序( 其实直接写 x: x[1] 就是按照第一个值排序. )
a = {'a': [1, 3], 'c': [3, 4], 'b': [0, 2], 'd': [2, 1]}
b = sorted(a.items(), key=lambda x: x[1][0], reverse=True)
# [('c', [3, 4]), ('d', [2, 1]), ('a', [1, 3]), ('b', [0, 2])]
# 按照列表其他元素排序 只需要修改列表对应的下标
a = {'a': [1, 3], 'c': [3, 4], 'b': [0, 2], 'd': [2, 1]}
b = sorted(a.items(), key=lambda x: x[1][1], reverse=True)
# [('c', [3, 4]), ('a', [1, 3]), ('b', [0, 2]), ('d', [2, 1])]
"""
总结: 此处使用lambda方法, x: x[1][1] 就可以看做是在访问字典的值,
想要按照哪个数值排序, 用相应的坐标对应即可, 但当字典过于复杂后,
应该选择用元组存储, 简化排序过程.
"""
方法二:
from operator import itemgetter
dict_list = [
{"ming": 87},
{"mei": 93},
{"hua": 68},
{"jon": 75},
{"ston": 100},
{"jack": 56}
]
mid_dict = {key: value for x in dict_list for key, value in x.items()}
mid_list = sorted(mid_dict.items(), key=itemgetter(1))
fin_list = [{x[0]: x[1]} for x in mid_list]
# 例子:
T=[{'xgei-0/0/1/1': '9'}, {'xgei-0/0/1/2': '20'},{'xgei-0/0/1/15': '12'}]
def Sorted_listdict(dict_list):
New_List=[]
New_D={}
# 格式写法
mid_dict = {key: value for x in dict_list for key, value in x.items()}
# 列表与字典的结构
#print (mid_dict)
ordered_dict = OrderedDict(sorted(mid_dict.items(), key=lambda t: int(t[1]), reverse=True))
print (type(ordered_dict),ordered_dict)
"""
<class 'collections.OrderedDict'>
OrderedDict(
[('xgei-0/0/1/2', '20'), ('xgei-0/0/1/15', '12'), ('xgei-0/0/1/1', '9')
)
"""
for x in ordered_dict:
New_D[x]=mid_dict[x]
New_List.append(New_D)
print (New_List)
return New_List
newlist = sorted(data, key=lambda k: k['PricingOptions']["Price"], reverse=True)
print(newlist)
"""
[{'PricingOptions': {'Price': 227243.14, 'Agents': [4056270]}},
{'PricingOptions': #{'Price': 51540.72, 'Agents': [4056270]}}
]
"""