> For the complete documentation index, see [llms.txt](https://m0uk4.gitbook.io/notebooks/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://m0uk4.gitbook.io/notebooks/mouka/python/python-tricks/zi-dian-pai-xu.md).

# 字典排序

```python
>>> xs = {'a': 4, 'b': 3, 'c': 2, 'd': 1}

>>> sorted(xs.items(), key=lambda x: x[1])    # 按value排序
[('d', 1), ('c', 2), ('b', 3), ('a', 4)]
>>> sorted(xs.items(), key=lambda x: x[0])    # 按key排序    
[('a', 4), ('b', 3), ('c', 2), ('d', 1)]    
# Or:

>>> import operator
>>> sorted(xs.items(), key=operator.itemgetter(1))
[('d', 1), ('c', 2), ('b', 3), ('a', 4)]
>>> sorted(xs.items(),key=operator.itemgetter(0))
[('a', 4), ('b', 3), ('c', 2), ('d', 1)]
```
