PyTricks-How to Sort a Python dict

字典的键值排序

import operator

# 1表示按照值排序
xs = {"a": 4, "b": 3, "c": 2, "d": 1, "f": 0, "e": 9}
print(dict(sorted(xs.items(), key=lambda x: x[1])))
print(dict(sorted(xs.items(), key=operator.itemgetter(1))))

# 0表示按照建排序
print(dict(sorted(xs.items(), key=lambda x: x[0])))
print(dict(sorted(xs.items(), key=operator.itemgetter(0))))
posted @ 2019-08-08 09:16  公众号python学习开发  阅读(176)  评论(0编辑  收藏  举报