一、字典按key值排序
1.实现代码:
d = {"a": 1, "c": 3, "b": 4, "d": 2}
# 基于key进行排序
def sort_dict_data(dict_data, reverse=False):
sorted_key = sorted(dict_data.keys(), reverse=reverse)
sorted_dict = {}
for key in sorted_key:
sorted_dict[key] = dict_data[key]
return sorted_dict
result = sort_dict_data(d)
print(result)
2.输出结果:
{'a': 1, 'b': 4, 'c': 3, 'd': 2}
二、字典按value值排序
按上例,如果要按照"events"的数量进行排序,那么我们要怎么样处理呢?
1.实现代码
d = {"a": 1, "c": 3, "b": 4, "d": 2}
# 基于value进行排序
def sort_dict_by_value(dict_data, reverse=False):
sorted_items = sorted(dict_data.items(), key=lambda x: x[1], reverse=reverse)
sorted_dict = {}
for item in sorted_items:
sorted_dict[item[0]] = item[1]
return sorted_dict
result = sort_dict_by_value(d)
print(result)
2.测试结果
{'a': 1, 'd': 2, 'c': 3, 'b': 4}
三、字段按多个value值进行排序
d = {
"user3": {
"name": "Tom",
"score": 89
},
"user2": {
"name": "John",
"score": 95
},
"user4": {
"name": "Adam",
"score": 89
},
"user1": {
"name": "Mary",
"score": 90
}
}
# 基于多个value进行排序
def sort_dict_by_multiple_value(dict_data, reverse=False):
sorted_items = sorted(dict_data.items(), key=lambda x: (x[1]["score"], x[1]["name"]), reverse=reverse)
sorted_dict = {}
for item in sorted_items:
sorted_dict[item[0]] = item[1]
return sorted_dict
result = sort_dict_by_multiple_value(d, reverse=True)
print(result)
2. 测试结果
{'user2': {'name': 'John', 'score': 95}, 'user1': {'name': 'Mary', 'score': 90}, 'user3': {'name': 'Tom', 'score': 89}, 'user4': {'name': 'Adam', 'score': 89}}
如上,我们先按照score从高到低排序,再按照name从大到小排序。
那么问题来了,如果我们需要将name改成按从小到大排序要怎么办呢?
d = {
"user3": {
"name": "Tom",
"score": 89
},
"user2": {
"name": "John",
"score": 95
},
"user4": {
"name": "Adam",
"score": 89
},
"user1": {
"name": "Mary",
"score": 90
}
}
# 基于多个value进行排序
def sort_dict_by_multiple_value(dict_data, reverse=False):
# if reverse:
# reverse = False
# else:
# reverse = True
sorted_items = sorted(dict_data.items(), key=lambda x: (-x[1]["score"], x[1]["name"].encode()), reverse=reverse)
sorted_dict = {}
for item in sorted_items:
sorted_dict[item[0]] = item[1]
return sorted_dict
result = sort_dict_by_multiple_value(d, reverse=False)
print(result)
测试结果:
{'user2': {'name': 'John', 'score': 95}, 'user1': {'name': 'Mary', 'score': 90}, 'user4': {'name': 'Adam', 'score': 89}, 'user3': {'name': 'Tom', 'score': 89}}