PyTricks-How to Sort a Python dict

mac2022-06-30  35

字典的键值排序

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))))

转载于:https://www.cnblogs.com/c-x-a/p/11319183.html

最新回复(0)