sorted

排序dict

默认以key排序

1
2
3
4
5
6
7
8
origin_dict = {
"kkk": 'k',
"bbb": '6',
"ccc": '1',
}

new_dict = sorted(origin_dict.items())
print(new_dict)

输出结果,默认是升序,如果需要降序,则设置reverse=False。

1
[('bbb', '6'), ('ccc', '1'), ('kkk', 'k')]

指定value排序

1
2
3
4
5
6
7
8
origin_dict = {
"kkk": 'k',
"bbb": '6',
"ccc": '1',
}

new_dict = sorted(origin_dict.items(), key=lambda item: item[1])
print(new_dict)

输出结果

1
[('ccc', '1'), ('bbb', '6'), ('kkk', 'k')]

如果修改item[0],则表示以key进行排序

排序list,元素为dict类型

示例代码1:单条件排序

1
2
3
4
5
6
7
8
9
10
11
12
13
obj_list = [
{
"age": 5
},
{
"age": 15
},
{
"age": 3
},
]
sorted_list = sorted (obj_list, key=lambda item: item['age'])
print (sorted_list)

输出结果

1
2
3
4
5
6
7
8
9
10
11
[
{
"age": 3
},
{
"age": 5
},
{
"age": 15
}
]


示例代码2:多条件排序

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import json

obj_list = [
{
"age": 5,
"order": "bbc"
},
{
"age": 5,
"order": "abc"
},
{
"age": 3,
"order": "heihei"
},
]
sorted_list = sorted (obj_list, key=lambda item: (item['age'], item['order']))
print (json.dumps(sorted_list))

输出结果

1
2
3
4
5
6
7
8
9
10
11
12
13
14
[
{
"age": 3,
"order": "heihei"
},
{
"age": 5,
"order": "abc"
},
{
"age": 5,
"order": "bbc"
}
]

默认以第一个字段age从小到大排序,如果age相等,再比较order字段


示例代码3:嵌套字典排序

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
import json

obj_list = [
{
"interface": {
"interface_id": 5,
"ordinal": 2,
},
"testcase_ids": [1]
},
{
"interface": {
"interface_id": 5,
"ordinal": 1,
},
"testcase_ids": [2]
},
{
"interface": {
"interface_id": 3,
"ordinal": 1,
},
"testcase_ids": [3]
},
]
sorted_list = sorted(obj_list, key=lambda item: (item['interface']['ordinal'], item['interface']['interface_id']))
print(json.dumps(sorted_list))

`

输出结果

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
[
{
"interface": {
"interface_id": 3,
"ordinal": 1
},
"testcase_ids": [
3
]
},
{
"interface": {
"interface_id": 5,
"ordinal": 1
},
"testcase_ids": [
2
]
},
{
"interface": {
"interface_id": 5,
"ordinal": 2
},
"testcase_ids": [
1
]
}
]

OrderedDict

字典排序生成

1
2
3
4
5
6
7
8
9
obj_list = {
'key3': {'order': 3},
'key2': {'order': 2},
'key1': {'order': 1},
'key5': {'order': 5},
'key6': {'order': 6},
}
sorted_dict = OrderedDict(sorted(obj_list.items(), key=lambda t: t[1]['order']))
print(sorted_dict)

输出结果

1
{"key1": {"order": 1}, "key2": {"order": 2}, "key3": {"order": 3}, "key5": {"order": 5}, "key6": {"order": 6}}