Skip to content

Commit e9bd64d

Browse files
committed
python dict sort
1 parent 51a77e6 commit e9bd64d

File tree

1 file changed

+13
-0
lines changed
  • docs/19_python内置常用算法和数据结构

1 file changed

+13
-0
lines changed

docs/19_python内置常用算法和数据结构/builtins.md

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -55,6 +55,19 @@ MAXINT = (1<<63) - 1
5555
MININT = ~MAXINT
5656
```
5757

58+
# python dict 排序
59+
60+
```py
61+
# 补充 python 根据 key,value 排序字典的
62+
d = {'d': 4, 'a': 1, 'b': 2, 'c':3}
63+
# sort by key and reverse
64+
dict(sorted(d.items())) # {'a': 1, 'b': 2, 'c': 3, 'd': 4}
65+
dict(sorted(d.items(), reverse=True)) # {'d': 4, 'c': 3, 'b': 2, 'a': 1}
66+
67+
# sort by value and reverse
68+
dict(sorted(d.items(), key = lambda kv:kv[1])) # {'a': 1, 'b': 2, 'c': 3, 'd': 4}
69+
dict(sorted(d.items(), key = lambda kv:kv[1], reverse=True)) # {'d': 4, 'c': 3, 'b': 2, 'a': 1}
70+
```
5871

5972
# 链表题目调试函数
6073

0 commit comments

Comments
 (0)