分享幾種python字典dict和串列list的排序方法。
字典(dict)排序
demo_dict = {
"key5": "value5",
"key3": "value3",
"key1": "value1",
"key2": "value2",
"key4": "value4",
}
sort_list = [(k, demo_dict[k]) for k in sorted(demo_dict.keys())]
reverse_sort_list = [(k, demo_dict[k]) for k in sorted(demo_dict.keys(), reverse=True)]
串列(list)排序
(1)串列list中是值valuedemo_list = [
"vlaue5",
"vlaue3",
"vlaue1",
"vlaue2",
"vlaue4"
]
sort_list = sorted(demo_list)
reverse_sort_list = sorted(demo_list, reverse=True)
(2)串列list中是字典dict
demo_list = [
{"key": "key5", "value": "value5"},
{"key": "key3", "value": "value3"},
{"key": "key1", "value": "value1"},
{"key": "key2", "value": "value2"},
{"key": "key4", "value": "value4"}
]
sort_list = sorted(demo_list, key=lambda k: k["key"])
reverse_sort_list = sorted(demo_list, key=lambda k: k["key"], reverse=True)
(3)串列list中是串列list
demo_list = [
["key5", "vlaue5"],
["key3", "vlaue3"],
["key1", "vlaue1"],
["key2", "vlaue2"],
["key4", "vlaue4"]
]
sort_list = sorted(demo_list, key=lambda k: k[0])
reverse_sort_list = sorted(demo_list, key=lambda k: k["key"], reverse=True)